Skip to content

Instantly share code, notes, and snippets.

@osyo-manga
Created October 18, 2015 10:12
Show Gist options
  • Select an option

  • Save osyo-manga/dcd5d6afbb45a6fd5a93 to your computer and use it in GitHub Desktop.

Select an option

Save osyo-manga/dcd5d6afbb45a6fd5a93 to your computer and use it in GitHub Desktop.
concept
class X
def self.concept name, &request
impl_name = "#{name}_#{request}"
alias_method impl_name, name
@@concept_methods ||= {}
@@concept_methods[name] ||= []
@@concept_methods[name].unshift [request, impl_name]
define_method(name){ |*args|
for request, name_ in @@concept_methods[name]
if request.(*args)
return __send__ name_, *args
end
end
}
impl_name
end
def plus a, b
p "plus by +"
a + b
end
concept :plus do |a, b|
a.class == b.class
end
def plus a, b
p "plus by string"
"#{a}#{b}"
end
concept :plus do |a, b|
a.class == String && b.class == String
end
end
p X.new.plus 1, 2
p X.new.plus "homu", "mami"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment