Class: Ruby::Utils::Param

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby_utils/param.rb

Instance Method Summary collapse

Constructor Details

#initialize(hash = {}) ⇒ Param

Returns a new instance of Param.



3
4
5
6
7
# File 'lib/ruby_utils/param.rb', line 3

def initialize(hash = {})
  @original_hash = hash

  define_methods(@original_hash)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args, &block) ⇒ Object



27
28
29
30
31
32
33
# File 'lib/ruby_utils/param.rb', line 27

def method_missing(name, *args, &block)
  if @original_hash.respond_to?(name)
    @original_hash.send(name)
  else
    super
  end
end

Instance Method Details

#all?(*locators) ⇒ Boolean

Return true if all of the values are set.

can_show_fullname = params.all?(“:user:name:first”, “:user:name:last”)

Returns:

  • (Boolean)


195
196
197
# File 'lib/ruby_utils/param.rb', line 195

def all?(*locators)
  locators.all? { |locator| getOrElse(locator) }
end

#deep_contains(needle, haystack) ⇒ Object

deep_contains(1, 1, b: 2) => true deep_contains(2, 1, b: 2) => false deep_contains(1, b: 1, 1, b: 2) => false deep_contains(1, b: 2, 1, b: 2) => true



132
133
134
135
136
137
138
139
140
141
# File 'lib/ruby_utils/param.rb', line 132

def deep_contains(needle, haystack)
  needle.all? do |key, val|
    haystack_val = haystack[key]
    if val.is_a?(Hash) && haystack_val.is_a?(Hash)
      deep_contains(val, haystack_val)
    else
      val == haystack_val
    end
  end
end

#define_methods(h) ⇒ Object



9
10
11
12
13
14
15
16
17
# File 'lib/ruby_utils/param.rb', line 9

def define_methods(h)
  h.each do |k, v|
    h.define_singleton_method(k) do
      v
    end

    define_methods(v) if v.is_a?(Hash)
  end
end

#defined?(locator) ⇒ Boolean

Return true if the value is set.

has_address = params.defined?(“:user:location:address”) has_address # => true

Returns:

  • (Boolean)


187
188
189
# File 'lib/ruby_utils/param.rb', line 187

def defined?(locator)
  !getOrElse(locator).nil?
end

#flatten(h) ⇒ Object

{ a: b: 1 } -> { :“a.b” => 1 }“}



153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
# File 'lib/ruby_utils/param.rb', line 153

def flatten(h)
  # use helper lambda 
  acc = ->(prefix, hash) {
    hash.inject({}) { |memo, (k, v)|
      key_s = k.to_s
      if !k.is_a?(Symbol) || key_s.include?(".")
        raise ArgumentError.new("Key must be a Symbol and must not contain dot (.). Was: '#{k.to_s}', (#{k.class.name})")
      end
      prefixed_key = prefix.nil? ? k : [prefix.to_s, key_s].join(".")
      if v.is_a? Hash
        memo.merge(acc.call(prefixed_key, v))
      else
        memo.merge(prefixed_key.to_sym => v)
      end
    }
  }

  acc.call(nil, h)
end

#get(key) ⇒ Object, Exception

Returns the value of the hash given a delimited key If not key is found an error is raised

@param key A delimited string key to find the value of the hash

> params.get(“.poll.user.profile.email”)

Returns:

  • (Object, Exception)

    Exception if no key is found or else the value



44
45
46
47
# File 'lib/ruby_utils/param.rb', line 44

def get(key)
  methods = key.scan(/[\w'-]+/)
  _get(methods, self)
end

#getOrElse(locator, default = nil) ⇒ Object

Get a value from hash. If it’s not set, return default value. If default value is not provided, return nil. Never throw exception.

ex: params.getOrElse(“:user:location:address”, “Street address”) # => “Betonimiehenkuja 5” params.getOrElse(“:user:location:zipcode”, “00000”) # => “00000” params.getOrElse(“:user:location:zipcode”, params.getOrElse(“:user:location:address”, “N/A”)) # => “Betonimiehenkuja 5”

TODO Add more args for fallbacks:

getOrElse(locator, [fallback_locator_1, … , fallback_locator_n], default)] params.getOrElse(“:user:location:zipcode”, “:user:location:address”, “N/A”) # => “Betonimiehenkuja 5” params.getOrElse(“:user:location:zipcode”, “:user:location:state”, “N/A”) # => “N/A” params.getOrElse(“:user:location:zipcode”, “:user:location:state”, “:user:location:country”, “N/A”) # => “Finland”



73
74
75
76
77
# File 'lib/ruby_utils/param.rb', line 73

def getOrElse(locator, default=nil)
  get(locator)
rescue NoMethodError
  default
end

#map(key, &block) ⇒ Object

Get a value from hash and map the value with block. If value is not set, do nothing.

> mappedParams = params.map(“:user:location:city”, &:upcase)

> mappedParams.get(:city) # => “HELSINKI”



84
85
86
87
# File 'lib/ruby_utils/param.rb', line 84

def map(key, &block)
  result = getOrElse(key)
  block.call(result) if result
end

#map_keys(h, &block) ⇒ Object



89
90
91
# File 'lib/ruby_utils/param.rb', line 89

def map_keys(h, &block)
  Hash[h.map { |(k, v)| [block.call(k), v] }]
end

#map_values(h, &block) ⇒ Object



93
94
95
96
97
98
# File 'lib/ruby_utils/param.rb', line 93

def map_values(h, &block)
  h.inject({}) do |memo, (k, v)|
    memo[k] = block.call(v)
    memo
  end
end

#object_to_hash(object) ⇒ Object

p = Person.new(“Foo”, email: “[email protected]”) object_to_hash(p) => “Foo” , email: “[email protected]



175
176
177
178
179
180
# File 'lib/ruby_utils/param.rb', line 175

def object_to_hash(object)
  object.instance_variables.inject({}) do |hash, var|
    hash[var.to_s.delete("@")] = object.instance_variable_get(var)
    hash
  end
end

#pluck(array_of_hashes, *keys) ⇒ Object

Select values by given keys from array of hash Usage: pluck([“John”, age: 15, “Joe”], :name, :age) => [“John”, “Joe”, 15]



115
116
117
118
119
# File 'lib/ruby_utils/param.rb', line 115

def pluck(array_of_hashes, *keys)
  array_of_hashes.map { |h|
    keys.map { |key| h[key] }
  }.flatten.compact
end

#respond_to?(name) ⇒ Boolean

Returns:

  • (Boolean)


19
20
21
22
23
24
25
# File 'lib/ruby_utils/param.rb', line 19

def respond_to?(name)
  if @original_hash.respond_to?(name)
    true
  else
    super
  end
end

#sub(h, *keys) ⇒ Object

Select a subset of the hash h using given set of keys. Only include keys that are present in h. Usage:

sub({first: "First", last: "Last", age: 55}, :first, :age, :sex)
=> {first: "First", age: 55}


105
106
107
108
109
110
# File 'lib/ruby_utils/param.rb', line 105

def sub(h, *keys)
  keys.reduce({}) do |sub_hash, k|
    sub_hash[k] = h[k] if h.has_key?(k)
    sub_hash
  end
end

#sub_eq(a, b, *keys) ⇒ Object

Return true if given subset of fields in both hashes are equal Usage:

suq_eq({a: 1, b: 2, c: 3}, {a: 1, b: 2, c: 4}, :a, :b) => true


124
125
126
# File 'lib/ruby_utils/param.rb', line 124

def sub_eq(a, b, *keys)
  a.slice(*keys) == b.slice(*keys)
end

#to_hObject Also known as: to_hash, as_hash



209
210
211
# File 'lib/ruby_utils/param.rb', line 209

def to_h
  @original_hash
end

#with(key) {|result| ... } ⇒ Object

Run a given block only if value is defined.

params.with(“:user:location:address”) { |address| puts “Address: #address”} } # => “Address: Betonimiehenkuja 5” params.with(“:user:location:city”) { |city| puts “City: #{}”}

Yields:

  • (result)


204
205
206
207
# File 'lib/ruby_utils/param.rb', line 204

def with(key, &block)
  result = getOrElse(key)
  yield(result) if result
end

#wrap_if_present(key, value) ⇒ Object

wrap_if_present(:wrap, 1} -> {a: 1} wrap_if_present(:wrap, {}} -> {} wrap_if_present(:wrap, nil) -> {}



146
147
148
149
150
# File 'lib/ruby_utils/param.rb', line 146

def wrap_if_present(key, value)
  Maybe(value).map { |v|
    Hash[key, v]
  }.or_else({})
end