Class: Class2

Inherits:
Object
  • Object
show all
Defined in:
lib/class2.rb,
lib/class2/version.rb

Defined Under Namespace

Modules: LowerCamelCase, SnakeCase, StrictConstructor, UpperCamelCase

Constant Summary collapse

CONVERSIONS =
{
  Array     => lambda { |v| "Array(#{v})" },
  Date      => lambda { |v| "#{v} && Date.parse(#{v})" },
  DateTime  => lambda { |v| "#{v} && DateTime.parse(#{v})" },
  Float     => lambda { |v| "#{v} && Float(#{v})" },
  Hash      => lambda { |v| sprintf "%s.respond_to?(:to_h) ? %s.to_h : %s", v, v, v },
  Integer   => lambda { |v| "#{v} && Integer(#{v})" },
  String    => lambda { |v| "#{v} && String(#{v})" },
  Time      => lambda { |v| "#{v} && Time.parse(#{v})" },
  TrueClass => lambda do |v|
    sprintf '["1", 1, 1.0, true].freeze.include?(%s.is_a?(String) ? %s.strip : %s)', v, v, v
  end
}
VERSION =
"0.6.0"

Class Method Summary collapse

Class Method Details

.autoload(namespace = Object, stack = nil) ⇒ Object

:nodoc:



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/class2.rb', line 62

def autoload(namespace = Object, stack = nil) # :nodoc:
  failure = lambda { |message|  abort "class2: cannot autoload class definitions: #{message}" }
  failure["cannot find the right caller"] unless (stack || caller).find do |line|
    # Ignore our autoload file and require()
    line.index("/class2/autoload.rb:").nil? && line.index("/kernel_require.rb:").nil? && line =~ /(.+):\d+:in\s+`\S/
  end

  # Give this precedence over global DATA constant
  data = String.new
  File.open($1) do |io|
    while line = io.gets
      if line == "__END__\n"
        data << line while line = io.gets
      end
    end
  end

  # Fallback to global constant if nothing found
  data = ::DATA.read if data.empty? && defined?(::DATA)
  failure["no data section found"] if data.empty?

  spec = JSON.parse(data)
  Class2.new(namespace, spec)
rescue IOError, SystemCallError, JSON::ParserError => e
  failure[e.message]
end

.new(*argz, &block) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/class2.rb', line 46

def new(*argz, &block)
  specs = argz
  namespace = Object

  if specs[0].is_a?(String) || specs[0].is_a?(Module)
    namespace = specs[0].is_a?(String) ? create_namespace(specs.shift) : specs.shift
  end

  specs.each do |spec|
    spec = [spec] unless spec.respond_to?(:each)
    spec.each { |klass, attributes| make_class(namespace, klass, attributes, block) }
  end

  nil
end