Class: Yampla::Build
- Inherits:
-
Object
- Object
- Yampla::Build
- Defined in:
- lib/yampla/build.rb
Defined Under Namespace
Classes: TemplateError
Instance Attribute Summary collapse
-
#data ⇒ Object
readonly
Returns the value of attribute data.
Instance Method Summary collapse
- #build_index(template, name = nil) ⇒ Object
- #build_items(template, name = nil) ⇒ Object
-
#initialize(yaml) ⇒ Build
constructor
A new instance of Build.
- #run(type, opt = {}) ⇒ Object
- #save(type, opt = {}) ⇒ Object
- #set_template(type, template) ⇒ Object
Constructor Details
#initialize(yaml) ⇒ Build
Returns a new instance of Build.
8 9 10 11 12 |
# File 'lib/yampla/build.rb', line 8 def initialize(yaml) @template = {} @yaml = yaml_parse(yaml) @data = yaml2object(@yaml) end |
Instance Attribute Details
#data ⇒ Object (readonly)
Returns the value of attribute data.
7 8 9 |
# File 'lib/yampla/build.rb', line 7 def data @data end |
Instance Method Details
#build_index(template, name = nil) ⇒ Object
33 34 35 36 |
# File 'lib/yampla/build.rb', line 33 def build_index(template, name=nil) raise TemplateError, 'Template for index not set.' unless template Liquid::Template.parse(template).render("#{name || 'items'}" => @data) end |
#build_items(template, name = nil) ⇒ Object
38 39 40 41 42 43 |
# File 'lib/yampla/build.rb', line 38 def build_items(template, name=nil) raise TemplateError, 'Template for items not set.' unless template @data.each_with_object({}) do |item, h| h[item.id] = Liquid::Template.parse(template).render("#{name || 'item'}" => item) end end |
#run(type, opt = {}) ⇒ Object
21 22 23 24 25 26 27 28 29 30 31 |
# File 'lib/yampla/build.rb', line 21 def run(type, opt={}) opt = {template:@template[type], name:nil}.merge(opt) case type when :index build_index(opt[:template], opt[:name]) when :items build_items(opt[:template], opt[:name]) else raise ArgumentError, "First argument must be :index or :items." end end |
#save(type, opt = {}) ⇒ Object
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
# File 'lib/yampla/build.rb', line 45 def save(type, opt={}) opt = {ext:@extname, name:nil, dir:'out'}.merge(opt) content = run(type, name:opt[:name]) ext = ".#{opt[:ext]}" if opt[:ext] dir = opt[:dir] Dir.mkdir(dir) unless Dir.exists?(dir) case type when :index path = File.join(dir, "index#{ext}") File.open(path, 'w') { |f| f.puts content } when :items content.each do |id, data| path = File.join(dir, "#{id}#{ext}") File.open(path, 'w') { |f| f.puts data } end end end |
#set_template(type, template) ⇒ Object
14 15 16 17 18 19 |
# File 'lib/yampla/build.rb', line 14 def set_template(type, template) unless [:index, :items].include?(type.intern) raise ArgumentError, "First argument must :index or :items" end @template[type] = parse_template(template) end |