我的 Rails 应用程序中有一个 ActiveRecord 模型,我想将它映射到其他一些 Ruby 对象。这些模型将命中外部 api,类之间的主要变化是字段名称和一些 api 细节。在下面的示例中,Person需要映射到其他两个 Api 特定类。
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
是否有可用的映射 gem 可以进行这种类型的映射?有没有其他人遇到过类似的映射问题,您是如何解决的?
如果我要自己推出,我会考虑某种散列来映射每个字段。
.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 wiki https://github.com/AutoMapper/AutoMapper/wiki/Projection