Created
December 4, 2013 18:27
-
-
Save foostan/7792852 to your computer and use it in GitHub Desktop.
Rubyで自由な形式のConfigファイルを読み込めるようにしてみる ref: http://qiita.com/foostan/items/6619624d30b5820d93e4
This file contains 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
class User | |
def hello | |
puts 'Hello World!' | |
end | |
end | |
config.user = User.new |
This file contains 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
require 'hashie' | |
module AppConfig | |
extend self | |
AppConfig.load(File.read(File.expand_path('~/.config.rb'))) | |
def load(file) | |
# default | |
config = Hashie::Mash.new | |
config.user = { | |
name: 'foo', | |
age: 25 | |
} | |
# overwirte | |
instance_eval(file) | |
config.each do |key, value| | |
attr_accessor key | |
send("#{key}=", value) | |
end | |
end | |
end |
This file contains 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
require '/path/to/appconfig.rb' | |
AppConfig.user.hello |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment