Sha256: fb2414488d8301b6ec79f3662d61093450fbec3629b2268b9d9ca302604efa16

Contents?: true

Size: 1.47 KB

Versions: 84

Compression:

Stored size: 1.47 KB

Contents

# encoding: utf-8

module EvalHelper
  # create attr_accessor + initialize code, for eval
  #
  # ==== Examples
  #
  # single case
  #
  #   class EvalHelperAttrAccessorInitTest
  #     include EvalHelper
  #
  #     def hoge(args)
  #       attr_accessor_init_code(args)
  #     end
  #   end
  #
  #   EvalHelperAttrAccessorInitTest.new.hoge('atr1')
  #
  # result
  #
  #   attr_accessor :atr1
  #
  #   def initialize(atr1)
  #     @atr1 = atr1
  #   end
  #
  # multi case
  #
  #   class EvalHelperAttrAccessorInitTest
  #     include EvalHelper
  #
  #     def hoge(args)
  #       attr_accessor_init_code(args)
  #     end
  #   end
  #
  #   EvalHelperAttrAccessorInitTest.new.hoge(['atr1', 'atr2'])
  #
  # result
  #
  #   attr_accessor :atr1, :atr2
  #
  #   def initialize(atr1, atr2)
  #     @atr1 = atr1
  #     @atr2 = atr2
  #   end
  #
  def attr_accessor_init_code(attribute)
    return '' unless [String, Array].include? attribute.class
    atrs = []
    if attribute.is_a? String
      atrs << attribute
    elsif attribute.is_a? Array
      atrs = attribute
    end

    accessors = atrs.reduce([]) { |ret, v|ret << ":#{v}" }.join(', ')
    init_variables = atrs.reduce([]) { |ret, v|ret << "#{v}" }.join(', ')
    set_variables = atrs.reduce([]) { |ret, v|ret << "  @#{v} = #{v}" }.join("\n")
    ret_code = <<-EOS
attr_accessor #{accessors}

def initialize(#{init_variables})
#{set_variables}
end
    EOS
  end
end

Version data entries

84 entries across 84 versions & 1 rubygems

Version Path
tbpgr_utils-0.0.90 lib/eval_helper/attr_accessor_init_code.rb
tbpgr_utils-0.0.89 lib/eval_helper/attr_accessor_init_code.rb
tbpgr_utils-0.0.88 lib/eval_helper/attr_accessor_init_code.rb
tbpgr_utils-0.0.87 lib/eval_helper/attr_accessor_init_code.rb
tbpgr_utils-0.0.86 lib/eval_helper/attr_accessor_init_code.rb
tbpgr_utils-0.0.85 lib/eval_helper/attr_accessor_init_code.rb
tbpgr_utils-0.0.84 lib/eval_helper/attr_accessor_init_code.rb
tbpgr_utils-0.0.83 lib/eval_helper/attr_accessor_init_code.rb
tbpgr_utils-0.0.82 lib/eval_helper/attr_accessor_init_code.rb
tbpgr_utils-0.0.81 lib/eval_helper/attr_accessor_init_code.rb
tbpgr_utils-0.0.80 lib/eval_helper/attr_accessor_init_code.rb
tbpgr_utils-0.0.79 lib/eval_helper/attr_accessor_init_code.rb
tbpgr_utils-0.0.78 lib/eval_helper/attr_accessor_init_code.rb
tbpgr_utils-0.0.77 lib/eval_helper/attr_accessor_init_code.rb
tbpgr_utils-0.0.76 lib/eval_helper/attr_accessor_init_code.rb
tbpgr_utils-0.0.75 lib/eval_helper/attr_accessor_init_code.rb
tbpgr_utils-0.0.74 lib/eval_helper/attr_accessor_init_code.rb
tbpgr_utils-0.0.73 lib/eval_helper/attr_accessor_init_code.rb
tbpgr_utils-0.0.72 lib/eval_helper/attr_accessor_init_code.rb
tbpgr_utils-0.0.71 lib/eval_helper/attr_accessor_init_code.rb