Skip to content

Instantly share code, notes, and snippets.

@markfeedly
Last active August 29, 2015 13:58
Show Gist options
  • Save markfeedly/10101641 to your computer and use it in GitHub Desktop.
Save markfeedly/10101641 to your computer and use it in GitHub Desktop.
my crap metaprogramming
# so I want to dry up this kind of method, which occurs only four times, but since I anticipate using this construct a few more times, and page.rb is looking long, the effort of metaprogramming seems worthwhile
# with I guess moving the defn of spec attr acessor out into an included module
# so here is the code to dry, shown for categories
def categories=(c)
if history.last.try(:new_record?)
history.last.categories = c
else
history.new(categories: c)
end
end
---------------
# I think I can rewrite this as the following
def self.special_attr_accessor(attr, set: rhs)
define_method "#{attr}=" do |rhs|
if history.last.try(:new_record?)
history.last.instance_variable_set "@#{attr}", set.(rhs)
else
history.new("#{attr}=": set.(rhs))
end
end
end
----------------------------
# and to add this getter
def categories
history.last.try(:categories)
end
# i add in a suitable spot
define_method "#{attr}" do
history.last.try("#{attr}")
end
------------------
Then I call as
special_attr_accessor :categories, set: ->(val){val}
special_attr_accessor :tags, set: ->(val){val}
# ... creator ... tags
though can the stab be removed here?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment