Class: Hash

Inherits:
Object show all
Defined in:
lib/rext/hash/helpers.rb

Instance Method Summary collapse

Instance Method Details

#apply_to(object) ⇒ Object

Apply values to object’s accessors.

Examples

class Foo
  attr_accessors :foo
  def initialize options = {}
    options.apply_to self
  end 
end 

foo = Foo.new :foo => 'bar'
foo.foo # => 'bar'

foo = Foo.new :something => 'else'
# => NoMethodError because :something= does not exist

See

* Hash#apply_to!


27
28
29
30
31
# File 'lib/rext/hash/helpers.rb', line 27

def apply_to object
  each do |key, value|
    object.send :"#{key}=", value
  end
end

#apply_to!(object) ⇒ Object

Apply values to object’s accessors, checking if the object responds to each key.

Examples

class Foo
  attr_accessors :foo
  def initialize options = {}
    options.apply_to! self
  end 
end 

foo = Foo.new :foo => 'bar'
foo.foo # => 'bar'

foo = Foo.new :something => 'else'
# => nothing is raised

See

* Hash#apply_to


57
58
59
60
61
# File 'lib/rext/hash/helpers.rb', line 57

def apply_to! object
  each do |key, value|
    object.send :"#{key}=", value if object.respond_to? :"#{key}="
  end
end

#delete_at(*keys) ⇒ Object Also known as: extract!

Delete key-value pairs, returning the values found using the keys passed. Aliased as extract!

Examples

options = { :width => 25, :height => 100 }
width, height = options.delete_at :width, :height  

width   # => 25
height  # => 100
options # => {}


88
89
90
# File 'lib/rext/hash/helpers.rb', line 88

def delete_at *keys
  keys.map { |key| delete key }
end

#switchifyObject

Return an array of switches and their arguments.

Examples

{ :use_foobar => true }.switchify   # => ['--use-foobar']
{ :use_foobar => false }.switchify  # => []
{ :interval => 15, :icon => :jpeg } # => ['--interval', '15', '--icon', 'jpeg']


103
104
105
106
107
108
109
110
# File 'lib/rext/hash/helpers.rb', line 103

def switchify
  inject [] do |args, (key, value)|
    next args unless value
    args << key.to_s.switchify
    args << (String === value ? value.inspect : value.to_s) unless value === true
    args
  end
end

#to_queryObject

Convert self to an HTTP query string.



66
67
68
69
70
71
72
# File 'lib/rext/hash/helpers.rb', line 66

def to_query
  if Rack::Utils.respond_to? :build_nested_query
    Rack::Utils.build_nested_query self
  else
    Rack::Utils.build_query self
  end
end