Last active
January 3, 2016 11:28
-
-
Save jadon1979/8455966 to your computer and use it in GitHub Desktop.
YAML to OpenStruct
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
| class SiteVariables < YamlToOpenStruct | |
| def initialize | |
| variables_yml = YAML::load(File.open('yaml_location')) | |
| @struct = convert_yml(variables_yml) | |
| end | |
| # send method calls to generated struct | |
| def method_missing(method, *args, &block) | |
| @struct.send(method, *args, &block) | |
| end | |
| end |
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
| class YamlToOpenStruct | |
| # pass YAML data and return an OpenStruct | |
| def convert_yml(yaml_data) | |
| convert_to_struct yaml_data | |
| end | |
| private | |
| def convert_to_struct(data) | |
| case data | |
| when Hash | |
| data = data.clone | |
| data.each { |k, v| data[k] = convert_to_struct(v) } | |
| OpenStruct.new(data) | |
| when Array | |
| data = data.clone | |
| data.map! { |ele| convert_to_struct(ele) } | |
| else | |
| data | |
| end | |
| end | |
| end |
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
| class YamlToOpenStruct | |
| # pass YAML data and return an OpenStruct | |
| def convert_yml(yaml_data) | |
| convert_to_struct yaml_data | |
| end | |
| private | |
| def convert_to_struct(data) | |
| case data | |
| when Hash | |
| data = data.clone | |
| data.each { |k, v| data[k] = convert_to_struct(v) } | |
| OpenStruct.new(data) | |
| when Array | |
| data = data.clone | |
| data.map! { |ele| convert_to_struct(ele) } | |
| else | |
| data | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment