Skip to content

Instantly share code, notes, and snippets.

@plus3x
Last active July 2, 2017 16:14
Show Gist options
  • Save plus3x/0418148678865237096b71f77baa51d3 to your computer and use it in GitHub Desktop.
Save plus3x/0418148678865237096b71f77baa51d3 to your computer and use it in GitHub Desktop.
Use extend module Settings or reuse one method from settings model
require 'active_record'
ActiveRecord::Base.establish_connection adapter: 'sqlite3', database: ':memory:'
ActiveRecord::Schema.define do
self.verbose = false
create_table :settings do |t|
t.string :name
t.integer :value
end
end
class Setting < ActiveRecord::Base
def self.alias(klass, name, selector)
klass.class_eval do
define_method(name) do
Setting.find_by(name: selector).value
end
private name
end
end
end
Setting.create! name: 'very_long_setting_name', value: 12
########################### First variant ###########################
class A
Setting.alias self, :short_name, 'very_long_setting_name'
def private_setting_short_name
short_name
end
end
A.new.private_setting_short_name # => 12
########################### Second variant ###########################
module Settings
def setting(name, selector:)
define_method(name) do
Setting.find_by(name: selector).value
end
private name
end
end
class B
extend Settings
setting :short_name, selector: 'very_long_setting_name'
def private_setting_short_name
short_name
end
end
B.new.private_setting_short_name # => 12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment