Skip to content

Instantly share code, notes, and snippets.

@chris-roerig
Last active July 14, 2020 20:59
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chris-roerig/e3506f24a17d66a8c152b1debc5b81d0 to your computer and use it in GitHub Desktop.
Save chris-roerig/e3506f24a17d66a8c152b1debc5b81d0 to your computer and use it in GitHub Desktop.
How to add macro style methods to a rails model
# 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