Module: ContentPackRails

Defined in:
lib/content_pack_rails.rb,
lib/content_pack_rails/version.rb

Constant Summary collapse

VERSION =
'1.0.0'

Class Method Summary collapse

Class Method Details

.init(configs = { pack_name: 'content_pack' }) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/content_pack_rails.rb', line 4

def self.init(configs = { pack_name: 'content_pack' })
  Module.new do
    silent = proc { |&block| v = $VERBOSE; $VERBOSE = nil; res = block.call; $VERBOSE = v; res }
    to_content_id = -> (id) { "_id_#{configs[:pack_name]}_#{id}".to_sym }

    define_method configs[:pack_name] do |id, content=nil, options={}, &block|
      _id = to_content_id.call(id)
      _block = proc { block.call(id) } if block
      options[:append] || options[:flush] || content_for?(_id) && return
      content_for(_id, content, options.slice(:flush), &_block)
      (silent.call { instance_variable_get(:"@_#{configs[:pack_name]}_ids") } ||
        instance_variable_set(:"@_#{configs[:pack_name]}_ids", Set.new)).add(_id)
    end

    define_method "provide_#{configs[:pack_name]}" do
      return unless (ids = silent.call { instance_variable_get(:"@_#{configs[:pack_name]}_ids") })
      ids.inject(nil) do |acc, id|
        return acc unless (content = content_for(id))
        acc ? acc.safe_concat(content) : content
      end
    end

    define_method "#{configs[:pack_name]}_get" do |id|
      content_for(to_content_id.call(id))
    end
  end
end