Class: Railstar::CodeList

Inherits:
Hash
  • Object
show all
Defined in:
lib/railstar/code_holder.rb

Instance Method Summary collapse

Constructor Details

#initialize(name) ⇒ CodeList



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/railstar/code_holder.rb', line 33

def initialize(name)
  puts "LOAD code #{name}"
  super(nil)

  @order = []
  @type = {}

  mode = "config"
  CSV.foreach(search_file(name), :encoding => "UTF-8") do |row|
    if mode == "config"
      if row.first == "type"
        @type[row[1].to_sym] = row[2]
      end
      mode = "header" if row.first == "#DATA"
    elsif mode == "header"
      @headers = row.map(&:to_sym)
      mode = "data"
    elsif mode == "data" && row.first.present?
      code = Code.new(@headers.zip(row).flatten, @type)
      raise DuplicateValue, code.value if self[code.value]
      self[code.value.to_s] = code
      self.instance_eval <<-EOS
        def #{code.key}
          self["#{code.value}"]
        end
      EOS
      if code.position.present?
        raise DuplicatePosition if @order[code.position]
        @order[code.position] = code.value
      end
    end
  end
  @order.compact!
end

Instance Method Details

#headersObject



68
69
70
# File 'lib/railstar/code_holder.rb', line 68

def headers
  @headers
end

#search_file(name) ⇒ Object

Raises:



72
73
74
75
76
77
78
79
80
# File 'lib/railstar/code_holder.rb', line 72

def search_file(name)
  files = [ File.join(Rails.root.to_s, 'resources', 'code', "#{name}.csv"),
            File.join(Railstar.code_dir, "#{name}.csv")
          ]
  files.each do |file|
    return file if File.exist?(file)
  end
  raise UndefinedCode
end

#to_opt(value = :name) ⇒ Object



82
83
84
# File 'lib/railstar/code_holder.rb', line 82

def to_opt(value=:name)
  @order.map{|k| [self[k].data(value), self[k]] }
end