module Aliyun::Log::Record::Field::ClassMethods

Public Instance Methods

field(name, options = {}) click to toggle source
# File lib/aliyun/log/record/field.rb, line 28
def field(name, options = {})
  type = options[:type] || :text
  unless PERMITTED_KEY_TYPES.include?(type)
    raise ArgumentError, "Field #{name} type(#{type}) error, key type only support text/long/double/json"
  end

  named = name.to_s
  if options[:log_tag]
    self.tag_attributes = tag_attributes.merge(name => { type: type }.merge(options))
  else
    self.attributes = attributes.merge(name => { type: type }.merge(options))
  end

  warn_about_method_overriding(name, name)
  warn_about_method_overriding("#{named}=", name)
  warn_about_method_overriding("#{named}?", name)

  define_attribute_method(name)

  generated_methods.module_eval do
    define_method(named) { read_attribute(named) }
    define_method("#{named}?") do
      value = read_attribute(named)
      case value
      when true        then true
      when false, nil  then false
      else
        !value.nil?
      end
    end
    define_method("#{named}=") { |value| write_attribute(named, value) }
  end
end
remove_field(field) click to toggle source
# File lib/aliyun/log/record/field.rb, line 62
def remove_field(field)
  field = field.to_sym
  attributes.delete(field) || raise('No such field')

  undefine_attribute_methods
  define_attribute_methods attributes.keys

  generated_methods.module_eval do
    remove_method field
    remove_method :"#{field}="
    remove_method :"#{field}?"
  end
end

Private Instance Methods

generated_methods() click to toggle source
# File lib/aliyun/log/record/field.rb, line 78
def generated_methods
  @generated_methods ||= begin
    Module.new.tap do |mod|
      include(mod)
    end
  end
end
warn_about_method_overriding(method_name, field_name) click to toggle source
# File lib/aliyun/log/record/field.rb, line 86
def warn_about_method_overriding(method_name, field_name)
  if instance_methods.include?(method_name.to_sym)
    logger.warn("Method #{method_name} generated for the field #{field_name} " \
                'overrides already existing method')
  end
end