Module: NoSE::DSL

Defined in:
lib/nose/util.rb

Overview

Helper functions for building DSLs

Class Method Summary collapse

Class Method Details

.mixin_fields(entities, cls) ⇒ void

This method returns an undefined value.

Add methods to the class which can be used to access entities and fields



234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
# File 'lib/nose/util.rb', line 234

def mixin_fields(entities, cls)
  entities.each do |entity_name, entity|
    # Add fake entity object for the DSL
    fake = Object.new

    # Add a method named by the entity to allow field creation
    cls.send :define_method, entity_name.to_sym, (proc do
      metaclass = class << fake; self; end

      # Allow fields to be defined using [] access
      metaclass.send :define_method, :[] do |field_name|
        if field_name == '*'
          entity.fields.values
        else
          entity.fields[field_name] || entity.foreign_keys[field_name]
        end
      end

      # Define methods named for fields so things like 'user.id' work
      entity.fields.merge(entity.foreign_keys).each do |field_name, field|
        metaclass.send :define_method, field_name.to_sym, -> { field }
      end

      fake
    end)
  end
end