Skip to content

Instantly share code, notes, and snippets.

@tansengming
Created July 9, 2012 07:37
Show Gist options
  • Save tansengming/3074833 to your computer and use it in GitHub Desktop.
Save tansengming/3074833 to your computer and use it in GitHub Desktop.
Ruby configure blocks
# How Clearance / Hoptoad does it
module Clearance
class << self
attr_accessor :configuration
end
def self.configure
self.configuration ||= Configuration.new
yield(configuration)
end
class Configuration
attr_accessor :mailer_sender
def initialize
@mailer_sender = 'donotreply@example.com'
end
end
end
# to use
Clearance.configure do |config|
config.mailer_sender = 'donotreply@example.com'
end
# How Devise does it
module Devise
mattr_accessor :mailer_sender # requires active support
@@mailer_sender = 'donotreply@example.com'
class << self
def setup
yield self
end
end
end
# to use
Devise.setup do |config|
config.mailer_sender = 'donotreply@example.com'
end
# references: http://robots.thoughtbot.com/post/344833329/mygem-configure-block
@cbetta
Copy link

cbetta commented Feb 6, 2015

I have a little problem with this. As soon as I edit any file in my rails project all classes are reloaded and initializers aren't rerun, leaving my config empty.

@cbetta
Copy link

cbetta commented Feb 6, 2015

I solved this by moving this to my lib folder, but I wonder if there's a different solution.

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