Module: Formie

Defined in:
lib/formie/engine.rb,
lib/formie.rb,
lib/formie/version.rb

Overview

rubocop: disable all

Defined Under Namespace

Classes: Engine

Constant Summary collapse

Rails6 =
Rails.version.to_f >= 6.0
PATH =
Rails6 ? 'app/views/formies' : 'app/formies'
VERSION =

2020-07-23

'1.0.3'

Class Method Summary collapse

Class Method Details

.define_formie(where, name, path) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/formie.rb', line 22

def self.define_formie(where, name, path)
  formiename = name

  where.send(:define_method, formiename, lambda { |*args, &block|
    # p "** called #{where} #{formiename}", args, block
    params = args.extract_options!
    options = {}
    if Rails6
      options[:template] = path.sub("#{Rails.root}/app/views", '')
    else
      options[:file] = path
    end
    options[:locals] = {}
    options[:locals].update params
    options[:locals].update formiename: formiename,
              block: block, form: self, args: args
    if defined?(controller) == 'method' &&
       controller.respond_to?(:render_to_body) # credits to MARS
      controller.render_to_body(options)
    else
      @template.render(options)
    end
  })
  # p "** defined  #{where} #{formiename}"
end

.load_formies(where, dir) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/formie.rb', line 48

def self.load_formies(where, dir)
  # avoid Dir.chdir (not thread safe)
  dir = File.join Rails.root, dir
  return unless File.exist?(dir)

  hsh = {}
  Dir.glob(File.join(dir, '**', '**')).sort.each { |path|
    base = File.basename(path).split('.').first
    hsh[base] = path unless hsh[base]
  }
  hsh.each { |name, path|
    next if File.new(path).mtime < @last_update

    x = File.expand_path(File.dirname(path))
    where.define_formie name, File.join(x, name)
  }
end

.reloadObject



9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/formie.rb', line 9

def self.reload
  if Rails6 && !File.directory?("#{Rails.root}/app/views/formies")
    raise 'Formies must be located in "app/views/formies" since Rails 6'
  end

  now = Time.now
  @last_update ||= Time.new(0)
  load_formies(::ActionView::Helpers::FormBuilder, "#{PATH}/forms")
  load_formies(::ActionView::Helpers::TextHelper,  "#{PATH}/application")
  load_formies(::ActionView::Helpers::TextHelper,  "#{PATH}/templates")
  @last_update = now
end