Created
July 26, 2012 01:59
-
-
Save keymon/3179821 to your computer and use it in GitHub Desktop.
Generating a configuration parser in ruby, like chef or others
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
| require "erb" | |
| class BigIpConfigurator | |
| @@resources = {} # Hash with all the resources defined | |
| # Define a resource, adding it to the list | |
| def self.resource(name, defaults, &block) | |
| @@resources[name] = { | |
| :defaults => defaults, | |
| :block => block | |
| } | |
| end | |
| attr_reader :resources, :environment_name | |
| def initialize | |
| @properties_context=[] | |
| @environment_name="" | |
| end | |
| # The magick method!!! | |
| def method_missing(meth, *args) | |
| # Check if a resource is defined, and if it is, try to load it. | |
| if @@resources.include?(meth) | |
| # Generate a new context for the properties with the defaults for | |
| # this resource type | |
| defaults = @@resources[meth][:defaults] | |
| @properties_context.push(defaults) | |
| begin | |
| yield # Load the properties | |
| ensure | |
| properties = @properties_context.pop | |
| end | |
| # Implements the posibility of define a name template | |
| id = args.first | |
| if !defaults[:name_template] | |
| name = id | |
| else | |
| name = ERB.new(properties[:name_template]).result(binding) | |
| end | |
| # Call the block that implements the resource | |
| @@resources[meth][:block].call(name, properties) | |
| # Load each of the properties if we are defining a resource | |
| elsif ! @properties_context.empty? and @properties_context.last.include?(meth) | |
| case args.size | |
| when 0 | |
| @properties_context.last[meth] = true | |
| when 1 | |
| @properties_context.last[meth] = args.first | |
| else | |
| @properties_context.last[meth] = args | |
| end | |
| else | |
| #Kernel.method_missing | |
| super | |
| #raise "Method missing: #{meth}" | |
| end | |
| end | |
| def load_config(str) | |
| self.instance_eval(str) | |
| end | |
| def environment(enviroment_name, &block) | |
| @environment_name = enviroment_name | |
| yield | |
| end | |
| # String class resource definition | |
| resource :string_class, { | |
| :members => [], | |
| :name_template => 'string_class_<%= id %>' | |
| } do |name, properties| | |
| puts name | |
| puts properties[:members] | |
| end | |
| end | |
| b = BigIpConfigurator.new | |
| b.load_config %q{ | |
| environment "qa1" do | |
| string_class "something" do | |
| name_template 'string_class_<%= id %>_<%= @environment_name %>' | |
| members 'a', 'e', 'i' | |
| end | |
| end | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment