Skip to content

Instantly share code, notes, and snippets.

@drnluz
Last active October 9, 2017 18:15
Show Gist options
  • Save drnluz/ce6e68ead91c77208f3299200f982ede to your computer and use it in GitHub Desktop.
Save drnluz/ce6e68ead91c77208f3299200f982ede to your computer and use it in GitHub Desktop.
C# like object mapper in Ruby
class AutoMapper
def initialize(klass, resolvers = {})
@klass = klass
@resolvers = resolvers
end
def map(object)
klass_instance = @klass.new
fields.each do |attribute|
klass_instance.send("#{attribute}=", value_for(attribute, object))
end
klass_instance
end
private
def value_for(attribute, object)
value_from_resolver(attribute, object) || value_from_object(attribute, object)
end
def value_from_resolver(attribute, object)
return unless @resolvers[attribute.to_sym].present?
@resolvers[attribute.to_sym].call(object)
end
def value_from_object(attribute, object)
object.public_send(attribute)
rescue NoMethodError => e
nil
end
def fields
active_record_columns || class_attributes
end
def active_record_columns
return unless @klass.ancestors.include?(ActiveRecord::Base)
@klass.column_names
end
def class_attributes
@klass.instance_methods(false)
.select { |method| method.to_s.end_with?('=') }
.map { |method| method.to_s.delete('=') }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment