method_missing example

Ruby code posted by Hugo Corbucci
created at 29 Dec 20:45, updated at 29 Dec 22:53

Edit | Back
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
require 'timeout'
class TimeoutWrapper
  def initialize(timeout_in_seconds, target)
    @timeout = timeout_in_seconds
    @target = target
  end
  def respond_to?(symbol, include_private=false)
    @target.respond_to?(symbol, include_private)
  end
  def method_missing(method_name, *args)
    status = Timeout::timeout(5) {
      @target.send(method_name, args)
    }
  end
end

class Trip < ActiveRecord::Base
  # Crappy backport of 'where' to rails 2.3
  def self.where(attribute_map)
    keys = attribute_map.keys.sort
    composed_name = keys.map(&:to_s).join('_and_')
    values = keys.map{|key|attribute_map[key]}
    send("find_by_#{composed_name}", values)
  end
end

Trip.where(:origin => 'ORD', :destination => 'SFO')

send("#{state}_price")

class Klass
  def hello(*args)
    "Hello " + args.join(' ')
  end
end
k = Klass.new
k.send :hello, "gentle", "readers"   #=> "Hello gentle readers"

class ClasslessObject
  def self.new(attributes)
    clazz = Class.new
    attributes.keys.each do |key|
      value = attributes[key]
      callable = value
      callable = lambda { || value } if !value.respond_to?(:call)
      clazz.send(:define_method, key, callable)
    end
    clazz.new
  end
end

object = ClasslessObject.new(
  :value_per_unit => 10,
  :quantity => 3,
  :total => lambda {|| value_per_unit * quantity}
)
object.methods - Object.new.methods
other = ClasslessObject.new(
  :value_per_unit => 15,
  :total => lambda {|number| value_per_unit * number}
)
other.methods - Object.new.methods

class Integer
  def to_roman
    # The answer
    'XLII' # Guaranteed to NOT be random
  end
end


Math::PI
 => 3.14159265358979 
Math.const_set('PI', 22.0/7)
Math::PI
 => 3.14285714285714 
1.74 KB in 4 ms with coderay