Sha256: 98ffe1084fb53eec905c2805270b76440a6a945aefd96bdecbda5649db4ec473

Contents?: true

Size: 916 Bytes

Versions: 58

Compression:

Stored size: 916 Bytes

Contents

# encoding: utf-8

# implement to_hash(instance_variable_name => key, instance_variable_value => value)
module AttributesHashable
  # create hash(instance_variable_name => key, instance_variable_value => value)
  #
  # class Hoge have two_attributes(:hoge, :hige)
  #   class Hoge
  #     include AttributesInitializable
  #     attr_accessor_init :hoge, :hige
  #     include AttributesHashable
  #   end
  #
  #   hoge = Hoge.new do |h|
  #     h.hoge = 'hoge'
  #     h.hige = 'hige'
  #   end
  #
  #   hoge.to_hash # => {:hoge=>"hoge", :hige=>"hige"}
  #
  # After include AttributesHashable, you can use Hash.try_convert.
  #   Hash.try_convert hoge # => {:hoge=>"hoge", :hige=>"hige"}
  def to_hash
    instance_variables.reduce({}) do |hash, var|
      hash[var.to_s.delete('@').to_sym] = instance_variable_get(var)
      hash
    end
  end

  alias_method :to_h, :to_hash
end

Version data entries

58 entries across 58 versions & 1 rubygems

Version Path
tbpgr_utils-0.0.151 lib/attributes_hashable.rb
tbpgr_utils-0.0.150 lib/attributes_hashable.rb
tbpgr_utils-0.0.149 lib/attributes_hashable.rb
tbpgr_utils-0.0.148 lib/attributes_hashable.rb
tbpgr_utils-0.0.147 lib/attributes_hashable.rb
tbpgr_utils-0.0.146 lib/attributes_hashable.rb
tbpgr_utils-0.0.145 lib/attributes_hashable.rb
tbpgr_utils-0.0.144 lib/attributes_hashable.rb
tbpgr_utils-0.0.143 lib/attributes_hashable.rb
tbpgr_utils-0.0.142 lib/attributes_hashable.rb
tbpgr_utils-0.0.141 lib/attributes_hashable.rb
tbpgr_utils-0.0.140 lib/attributes_hashable.rb
tbpgr_utils-0.0.139 lib/attributes_hashable.rb
tbpgr_utils-0.0.138 lib/attributes_hashable.rb
tbpgr_utils-0.0.137 lib/attributes_hashable.rb
tbpgr_utils-0.0.136 lib/attributes_hashable.rb
tbpgr_utils-0.0.135 lib/attributes_hashable.rb
tbpgr_utils-0.0.134 lib/attributes_hashable.rb
tbpgr_utils-0.0.133 lib/attributes_hashable.rb
tbpgr_utils-0.0.132 lib/attributes_hashable.rb