Sha256: d018c44131ff33bd67996cb3846d2e4d25d27e71792e626cc6332562b46b55fb

Contents?: true

Size: 1.59 KB

Versions: 1

Compression:

Stored size: 1.59 KB

Contents

module NsOptions

  class Option
    autoload :Boolean, 'ns-options/option/boolean'

    attr_accessor :name, :value, :type_class, :rules

    def initialize(name, type_class, rules = {})
      self.name = name.to_s
      self.type_class = self.usable_type_class(type_class)
      self.rules = rules
      self.value = rules[:default]
    end

    def value
      if self.type_class == NsOptions::Option::Boolean
        @value and @value.actual
      else
        @value
      end
    end

    def value=(new_value)
      @value = if (new_value.kind_of?(self.type_class)) || new_value.nil?
        new_value
      else
        self.coerce(new_value)
      end
    end

    def is_set?
      self.value.respond_to?(:is_set?) ? self.value.is_set? : !self.value.nil?
    end

    def required?
      !!self.rules[:required] || !!self.rules[:require]
    end

    def ==(other)
      [ :name, :type_class, :rules, :value ].inject(true) do |bool, attribute|
        bool && (self.send(attribute) == other.send(attribute))
      end
    end

    protected

    def coerce(new_value)
      if [ Integer, Float, String ].include?(self.type_class)
        # ruby type conversion, i.e. String(1)
        Object.send(self.type_class.to_s.to_sym, new_value)
      elsif self.type_class == Hash
        {}.merge(new_value)
      else
        self.type_class.new(new_value)
      end
    end

    def usable_type_class(type_class)
      if type_class == Fixnum
        Integer
      elsif [ TrueClass, FalseClass ].include?(type_class)
        NsOptions::Option::Boolean
      else
        (type_class || String)
      end
    end

  end

end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
ns-options-0.1.1 lib/ns-options/option.rb