Module: Hashing

Defined in:
lib/hashing.rb,
lib/hashing/ivar.rb,
lib/hashing/version.rb

Defined Under Namespace

Modules: Hasherizer Classes: Ivar, UnconfiguredIvar

Constant Summary collapse

VERSION =
"0.0.1"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(client_class) ⇒ Object

Inject the public api into the client class.

When ‘Hashing` is included, the host class will gain the `.from_hash({})` method and the `#to_h` instance method. Another method that will be added is the private class method `.hasherize` will be added so you can indicate what ivars do you want in your sarialized objects.

Examples:

including Hashing

require 'hashing'

class File
  include Hashing
  hasherize :path, :commit

  def initialize(path, commit)
    @path, @commit = path, commit
  end
end

Since:

  • 0.0.1



36
37
38
# File 'lib/hashing.rb', line 36

def self.included(client_class)
  client_class.extend Hasherizer
end

Instance Method Details

#meta_data(name, value) ⇒ Object



40
41
42
43
44
# File 'lib/hashing.rb', line 40

def (name, value)
  @_hashing_meta_data ||= { __hashing__: { types: {} } }
  @_hashing_meta_data[:__hashing__][:types][name] = value
  @_hashing_meta_data
end

#to_hObject

The ‘Hash` returned by `#to_h` will be formed by keys based on the ivars names passed to `hasherize` method.

Examples:

File hahserized (which include ‘Hashing`)


file = File.new 'README.md', 'cfe9aacbc02528b'
file.to_h
# => { path: 'README.md', commit: 'cfe9aacbc02528b' }


55
56
57
58
59
60
61
62
63
64
# File 'lib/hashing.rb', line 55

def to_h
  hash_pairs = self.class.ivars.map { |ivar|
    value = instance_variable_get "@#{ivar}"
    if value.respond_to? :map
       ivar.to_sym, value.first.class
    end
    [ivar.to_sym, ivar.to_h(value)]
  }
  Hash[hash_pairs].merge(@_hashing_meta_data || {})
end