Created
July 23, 2015 13:51
-
-
Save saturnflyer/8788d60a3b5505a2fdf9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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