« Back to Index

Ruby Meta Programming: Dynamically create Class methods with values populated from YAML config

View original Gist on GitHub

Config.yaml

CERT_PATH: "/Users/markmcdonnell/.pki/Certificate.pem"
CA_PATH: "/Users/markmcdonnell/.pki/ca.pem"
DEV_KEY: "12345a6b78d90e1f2gh345ijk6l78m90"
MEMBER_TOKEN: "00000a0b00d00e0f0gh000ijk0l00m00"
JIRA_ENDPOINT: "https://jira.domain.com/rest/api/2"
TRELLO_BOARD: "Tasks"
TRELLO_BACKLOG: "Up Next"
TRELLO_INPROGRESS: "In Progress"

Jello::Config.rb

module Jello
  class Config
    class << self
      private

      def create_methods(items)
        items.each do |item|
          define_singleton_method item.downcase do
            @@config[item]
          end
        end
      end

      def get_config
        @@config ||= YAML.load(File.read "config/development.yaml")
      end
    end

    create_methods get_config.keys
  end
end

# Just verify that things that shouldn't be accessible, definitely aren't accessible

Jello::Config.get_config
# NoMethodError: private method `get_config' called for Jello::Config:Class

Jello::Config.config
# NoMethodError: undefined method `config' for Jello::Config:Class

Jello::Config.DEV_KEY
# NoMethodError: undefined method `DEV_KEY' for Jello::Config:Class

Jello::Config.dev_key
# "12345a6b78d90e1f2gh345ijk6l78m90" (not real dev key obviously)