Module: ParamAccessor
- Included in:
- CommonParams, Rubylet::WarTask, RubyletDescriptor, StaticFileFilter
- Defined in:
- lib/rubylet/war_task.rb
Instance Method Summary collapse
-
#param_accessor(sym, default = nil, &block) ⇒ Object
Define a ‘param’, like attr_accessor, but with an optional default value.
Instance Method Details
#param_accessor(sym, default = nil, &block) ⇒ Object
Define a ‘param’, like attr_accessor, but with an optional default value. If params are defined as objects that respond to :call (e.g. a Proc) or a block is given, the proc or block will be instance_eval’ed in the context of the instance once on first read, after which the value is cached and returned on subsequent reads.
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
# File 'lib/rubylet/war_task.rb', line 18 def param_accessor(sym, default = nil, &block) if !default.nil? && block_given? raise ArgumentError, 'both default value and block may not be given' end iv = "@#{sym}" define_method(sym) do v = instance_variable_get(iv) val = if !v.nil? v elsif !default.nil? default elsif block_given? block else nil end if val.respond_to?(:call) newval = instance_eval(&val) instance_variable_set(iv, newval) newval else val end end define_method("#{sym}=") do |val| instance_variable_set(iv, val) end end |