2012-12-22 50 views
3

我在我的Rails應用程序中有一個ActiveRecord模型,我想要映射到其他Ruby對象。這些模型將觸及外部API,並且類之間會改變的主要內容是字段名稱和一些API特性。在下面的例子中,Person需要映射到其他兩個Api特定的類。有沒有一種方法可以輕鬆映射Ruby中的對象?

class Person 
    include Virtus 

    attribute :first_name, String 
    attribute :last_name, String 
    attribute :gender, String 
end 

class PersonApi1 
    include Virtus 

    attribute :forename, String 
    attribute :surname, String 
    attribute :gender, String 
end 

class PersonApi2 
    include Virtus 

    attribute :firstname, String 
    attribute :secondname, String 
    attribute :gender, String 
end 

是否有映射寶石可用,可以做這種類型的映射?是否有其他人遇到類似的地圖問題,你是如何找到它的?

如果我要推出自己的產品,我會考慮某種散列來映射出每個字段。

.net世界有Automapper,你可以在這裏說下面的東西。 Ruby中有類似的東西嗎?

public class CalendarEvent 
{ 
    public DateTime Date { get; set; } 
    public string Title { get; set; } 
} 

public class CalendarEventForm 
{ 
    public DateTime EventDate { get; set; } 
    public int EventHour { get; set; } 
    public int EventMinute { get; set; } 
    public string Title { get; set; } 
} 

//AutoMapper mapping 

Mapper.CreateMap<CalendarEvent, CalendarEventForm>() 
    .ForMember(dest => dest.EventDate, opt => opt.MapFrom(src => src.EventDate.Date)) 
    .ForMember(dest => dest.EventHour, opt => opt.MapFrom(src => src.EventDate.Hour)) 
    .ForMember(dest => dest.EventMinute, opt => opt.MapFrom(src => src.EventDate.Minute)); 

從automapper維基https://github.com/AutoMapper/AutoMapper/wiki/Projection

回答

3

我不知道這是否任何寶石的,所以我昨天把一個一起 - 試試看,如果你想 - https://github.com/house9/simple_attribute_mapper

更新:版本0.0.2現在支持以下映射

  • 默認(源和目標匹配屬性名稱)
  • 標準源到目標的屬性
  • 嵌套源到目標的屬性
  • 複合物(拉姆達風格)源到目標的屬性
相關問題