Module: Lookbook::Params

Defined in:
lib/lookbook/params.rb

Class Method Summary collapse

Class Method Details

.build_param(param, default: nil, **opts) ⇒ Object



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

def build_param(param, default: nil, **opts)
  input, options_str = param.text.present? ? param.text.split(" ", 2) : [nil, ""]
  type = param.types&.first
  options = if options_str.present? && options_str.end_with?(".json")
    json_path = if options_str.start_with?(".")
      File.expand_path(options_str, File.dirname(param.object.files.first[0]))
    else
      Rails.root.join(options_str)
    end
    JSON.parse(File.read(json_path))
  else
    YAML.safe_load(options_str || "~")
  end
  input ||= guess_input(type, default)
  type ||= guess_type(input, default)
  {
    name: param.name,
    input: input_text?(input) ? "text" : input,
    input_type: (input if input_text?(input)),
    options: options,
    type: type,
    default: default
  }
end

.cast(value, type = "String") ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/lookbook/params.rb', line 48

def cast(value, type = "String")
  case type.downcase
  when "symbol"
    value.presence&.delete_prefix(":")&.to_sym
  when "hash"
    result = safe_parse_yaml(value, {})
    unless result.is_a? Hash
      Lookbook.logger.debug "Failed to parse '#{value}' into a Hash"
      result = {}
    end
    result
  when "array"
    result = safe_parse_yaml(value, [])
    unless result.is_a? Array
      Lookbook.logger.debug "Failed to parse '#{value}' into an Array"
      result = []
    end
    result
  when "datetime"
    begin
      result = DateTime.parse(value)
    rescue Date::Error
      Lookbook.logger.debug "Failed to parse '#{value}' into a DateTime"
      result = DateTime.now
    end
    result
  else
    begin
      type_class = "ActiveModel::Type::#{type}".constantize
      type_class.new.cast(value)
    rescue NameError
      raise ArgumentError, "'#{type}' is not a valid param type to cast to."
    end
  end
end

.parse_method_param_str(param_str) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/lookbook/params.rb', line 31

def parse_method_param_str(param_str)
  return nil if param_str[0].nil? || param_str[1].nil?
  name = param_str[0].chomp(":")
  value = param_str[1]&.strip
  value = case value
  when "nil"
    nil
  else
    if value&.first == ":"
      value.delete_prefix(":").to_sym
    else
      YAML.safe_load(value)
    end
  end
  [name, value]
end