Module: LazyRecord::Methods
- Defined in:
- lib/lazy_record/methods.rb
Overview
Macro for dynamic instance method generation. Best to use for one-liners.
Constant Summary collapse
- METHODS_MODULE_NAME =
:DynamicMethods
Instance Method Summary collapse
-
#lr_method(method_name, method) ⇒ Symbol
Defines an instance method on the calling class.
Instance Method Details
#lr_method(method_name, method) ⇒ Symbol
Defines an instance method on the calling class. The first agrument is a symbol that names the method. The second argument should be a lambda that defines the method execution. The method argument could technically be any object that responds to #to_proc and returns a Proc, but lambdas with their arity restrictions are preferred.
Example
class Thing < LazyRecord::Base
lr_method :say_hi, -> { "Hi from #{self}" }
end
thing = Thing.new # => #<Thing>
thing.say_hi # => "Hi from #<Thing:0x007fb9629c6260>"
28 29 30 31 32 33 34 35 36 |
# File 'lib/lazy_record/methods.rb', line 28 def lr_method(method_name, method) mod = get_or_set_mod(METHODS_MODULE_NAME) mod.module_eval do define_method(method_name.to_sym, &method) end include mod unless include?(mod) end |