Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to easily map between objects in Ruby?

I have an ActiveRecord model in my rails app which I would like to map to some other Ruby object. These models will hit external apis and the main thing that will change between the classes is the field name and some api specifics. In the example below the Person needs to map to the other two Api specific classes.

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

Is there a mapping gem available that can do this type of mapping? Has anyone else come across a similar mapping problem and how have you approached it?

If I were to roll my own I would think about some sort of hash to map out each of the fields.

The .net world has Automapper where you can say something like below. Is something similar available in 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));

From the automapper wiki https://github.com/AutoMapper/AutoMapper/wiki/Projection

like image 405
ruhz Avatar asked Oct 15 '25 16:10

ruhz


1 Answers

I don't know of any gem that does this, so I put one together yesterday - give it a try if you want - https://github.com/house9/simple_attribute_mapper

UPDATE: version 0.0.2 now supports the following mappings

  • default (source and target matching attribute names)
  • standard source to target attribute
  • nested source to target attribute
  • composite (lambda style) source to target attribute
like image 74
house9 Avatar answered Oct 17 '25 05:10

house9



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!