Skip to content

Instantly share code, notes, and snippets.

@arekt
Created July 28, 2012 21:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arekt/3194805 to your computer and use it in GitHub Desktop.
Save arekt/3194805 to your computer and use it in GitHub Desktop.
Delegating methods to some class
class AbstractModel
def self.set_target(model_name)
@@model_name = model_name
AbstractModel.class.delegate :find, :to => :"#{@@model_name}"
AbstractModel.class.delegate :all, :to => :"#{@@model_name}"
end
end
#AbstractModel.set_target("Product")
#AbstractModel.find(1)
class AbstractModel
class Product
delegate :find, :to => :"::Product"
end
class Article
delegate :find, :to => :"::Article"
end
def self.build(model_name)
case model_name
when "Product"
AbstractModel::Product.new
when "Article"
AbstractModel::Article.new
end
end
end
#b = AbstractModel.build("Product")
#b.find(1)
class AbstractModel
def self.build(model_name)
eval "class #{model_name.camelize}
delegate :find, :to => ::#{model_name.camelize}
end
#{model_name.camelize}.new"
end
end
# b = AbstractModel.build("Product")
# c = AbstractModel.build("Article")
# d = AbstractModel::Article.new
# b.find(1)
# c.find(1)
# d.find(1)
class AbstractModel
def self.build(model_name, methods = [])
@model_name = model_name
@methods = methods
eval "class #{name_for_class}
#{delegate_body}
#{name_for_class}.new
end "
end
private
def self.delegate_body
@methods.map do |m|
"delegate :#{m}, :to => :\"#{@model_name.camelize}\""
end.join("\n")
end
def self.name_for_class
@model_name.gsub('.','_').camelize
end
end
# d = AbstractModel.build("Article",['all'])
# c = AbstractModel.build("Article.first",['title'])
# puts d.all
# puts c.title
@arekt
Copy link
Author

arekt commented Jul 28, 2012

Probably I should change name for something like Interface or MagicBinding

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment