Class: Object

Inherits:
BasicObject
Defined in:
lib/rext/object/helpers.rb,
lib/rext/object/metaclass.rb

Instance Method Summary collapse

Instance Method Details

#indifferent_hashObject

Returns a hash indifferent to symbols or strings for accessor keys.

Examples

hash = indifferent_hash
hash['foo'] = 'bar'

hash[:foo]  #=> 'bar'
hash['foo'] #=> 'bar'


17
18
19
# File 'lib/rext/object/helpers.rb', line 17

def indifferent_hash
  Hash.new { |hash, key| hash[key.to_s] if key.is_a? Symbol }
end

#meta_def(name, &block) ⇒ Object Also known as: metadef

Define a singleton method.



24
25
26
# File 'lib/rext/object/metaclass.rb', line 24

def meta_def name, &block
  meta_eval { define_method name, &block }
end

#meta_eval(string = nil, &block) ⇒ Object Also known as: metaeval

Evaluate a string or block in context to this object metaclass.



15
16
17
18
# File 'lib/rext/object/metaclass.rb', line 15

def meta_eval string = nil, &block
  return metaclass.class_eval(string) if string
  metaclass.class_eval &block
end

#metaclassObject

Return the metaclass of this object.



7
8
9
# File 'lib/rext/object/metaclass.rb', line 7

def metaclass
  class << self; self end
end

#returning(value) {|value| ... } ⇒ Object

Yield and return value.

Examples

people = []
people << 'tj'
people << 'foo'

returning [] do |people|
  people << 'tj'
  people << 'foo'
end

Yields:

  • (value)


36
37
38
39
# File 'lib/rext/object/helpers.rb', line 36

def returning value, &block
  yield value
  value
end

#try(times = 1, options = {}, &block) ⇒ Object

Retry a block of statements upto a number of times. When no error is raised the value returned by block is simply returned.

Examples

try 3 do
  open 'http://vision-media.ca'
end
# => allows 3 tries to fetch the response


54
55
56
57
58
# File 'lib/rext/object/helpers.rb', line 54

def try times = 1, options = {}, &block
  yield
rescue options[:on] || Exception
  retry if (times -= 1) > 0
end