Last active
July 14, 2020 20:59
-
-
Save chris-roerig/e3506f24a17d66a8c152b1debc5b81d0 to your computer and use it in GitHub Desktop.
How to add macro style methods to a rails model
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Rails Concern | |
# models/concerns/nicknameable.rb | |
module Nicknameable | |
extend ActiveSupport::Concern | |
included do | |
def self.nicknames(*args) | |
define_method("nicknames") { args } | |
end | |
nicknames | |
end | |
end | |
# /models/person.rb | |
class Person < ActiveRecord::Base | |
include Nicknameable | |
nicknames "foo", "bar" | |
end | |
# person = Person.new | |
# person.nicknames # => ["foo", "bar"] | |
# In pure Ruby | |
class Person | |
def self.nicknames(*args) | |
define_method(nicknames) { args } | |
end | |
nicknames :foo, :bar | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment