Created
February 7, 2012 10:44
-
-
Save masapico/1759063 to your computer and use it in GitHub Desktop.
Ruby Configuration pattern...
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
| # Hash | |
| class MyClass | |
| def initialize | |
| @config = { | |
| name: "default name", | |
| mail: "default mail" | |
| } | |
| end | |
| def set_config | |
| yield @config | |
| end | |
| end | |
| mc = MyClass.new | |
| mc.set_config do |config| | |
| config[:name] = "name changed" | |
| config[:mail] = "mail changed" | |
| end | |
| p mc #=>#<MyClass:0x7a34f0 @config={:name=>"name changed", :mail=>"mail changed"}> | |
| # attr_accessor | |
| class MyClass2 | |
| attr_accessor :name, :mail | |
| @@default = { | |
| name: "default name", | |
| mail: "default mail" | |
| } | |
| def initialize | |
| @@default.each_pair {|k, v| self.send("#{k}=", v)} | |
| end | |
| def config | |
| return self | |
| end | |
| def set_config | |
| yield config | |
| end | |
| end | |
| mc2 = MyClass2.new | |
| mc2.set_config do |sc| | |
| sc.name = "name changed" | |
| sc.mail = "main changed" | |
| end | |
| p mc2 #=>#<MyClass2:0x7a2c50 @name="name changed", @mail="main changed"> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment