Skip to content

Instantly share code, notes, and snippets.

@saturnflyer
Created July 23, 2015 13:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saturnflyer/8788d60a3b5505a2fdf9 to your computer and use it in GitHub Desktop.
Save saturnflyer/8788d60a3b5505a2fdf9 to your computer and use it in GitHub Desktop.
# 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