Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
# This is designed to be used in cell classes but will work with any class
# which has a 'model' method.
#
# Example:
#
# class UserCell < Cell::ViewModel
# extend ModelFeature
#
# model_feature :name
# end
#
# This will create an instance method 'name' which will check
# if the model responds to :[] and can access attributes
# like a hash model[:name] or falls back to model.name.
module ModelFeature
def model_feature(name)
begin
mod = const_get(:Features)
rescue NameError
mod = Module.new
const_set(:Features, mod)
include mod
end
mod.send(:define_method, name) do
if model.respond_to?(:[]) && !model.is_a?(Array)
model[name]
else
model.__send__(name)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment