Module: FunctionalDelegator::ClassMethods

Defined in:
lib/functional_delegator.rb

Instance Method Summary collapse

Instance Method Details

#functional_delegate(*keys) ⇒ Object

class Page

attr_reader :url, :protocol

def initialize(url, protocol)
  @url = url
  @protocol = protocol
end

def self.get(url)
  Net::HTTP.get(URI.parse(url))
end

def self.post(url, body)
  Net::HTTP.post(URI.parse(url))
end

def self.head(url, protocol)
  Net::HTTP.head(URI.parse(url), protocol)
end

functional_delegate :get, :post,  :attributes => :url
functional_delegate :head,        :attributes => [:url, :protocol]

end

Page.new(“www.dynport.de”).get # delegates to Page.get(“www.dynport.de”) Page.new(“www.dynport.de”).post(“the body”) # delegates to Page.post(“www.dynport.de”, “the body”) Page.new(“www.dynport.de”, “HTTP/1.1”).head # delegates to Page.head(“www.dynport.de”, “HTTP/1.1”)



30
31
32
33
34
35
36
37
38
# File 'lib/functional_delegator.rb', line 30

def functional_delegate(*keys)
  raise "ERROR: last argument must be e.g. :attributes => [:url]" if !keys.last.is_a?(Hash) || !keys.last.has_key?(:attributes)
  keys[0..-2].each do |method|
    define_method(method) do |*args|
      all_args = [keys.last[:attributes]].flatten.map { |att| self.send(att) } + args
      self.class.send(method, *all_args)
    end
  end
end