Class: React::Generators::ComponentGenerator

Inherits:
Rails::Generators::NamedBase
  • Object
show all
Defined in:
lib/generators/react/component_generator.rb

Constant Summary collapse

REACT_PROP_TYPES =
{
  "node" => "PropTypes.node",
  "bool" => "PropTypes.bool",
  "boolean" => "PropTypes.bool",
  "string" => "PropTypes.string",
  "number" => "PropTypes.number",
  "object" => "PropTypes.object",
  "array" => "PropTypes.array",
  "shape" => "PropTypes.shape({})",
  "element" => "PropTypes.element",
  "func" => "PropTypes.func",
  "function" => "PropTypes.func",
  "any" => "PropTypes.any",

  "instanceOf" => lambda { |type|
    "PropTypes.instanceOf(#{type.to_s.camelize})"
  },

  "oneOf" => lambda { |*options|
    enums = options.map { |k| "'#{k}'" }.join(",")
    "PropTypes.oneOf([#{enums}])"
  },

  "oneOfType" => lambda { |*options|
    types = options.map { |k| lookup(k.to_s, k.to_s).to_s }.join(",")
    "PropTypes.oneOfType([#{types}])"
  }
}.freeze
TYPESCRIPT_TYPES =
{
  "node" => "React.ReactNode",
  "bool" => "boolean",
  "boolean" => "boolean",
  "string" => "string",
  "number" => "number",
  "object" => "object",
  "array" => "Array<any>",
  "shape" => "object",
  "element" => "object",
  "func" => "object",
  "function" => "object",
  "any" => "any",

  "instanceOf" => lambda { |type|
    type.to_s.camelize
  },

  "oneOf" => lambda { |*opts|
    opts.map { |k| "'#{k}'" }.join(" | ")
  },

  "oneOfType" => lambda { |*opts|
    opts.map { |k| ts_lookup(k.to_s, k.to_s).to_s }.join(" | ")
  }
}.freeze

Instance Method Summary collapse

Instance Method Details

#create_component_fileObject



126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
# File 'lib/generators/react/component_generator.rb', line 126

def create_component_file
  template_extension = detect_template_extension
  # Prefer Shakapacker to Sprockets:
  if shakapacker?
    new_file_name = file_name.camelize
    extension = if options[:coffee]
                  "coffee"
                elsif options[:ts]
                  "tsx"
                else
                  "js"
                end
    target_dir = webpack_configuration.source_path
                                      .join("components")
                                      .relative_path_from(::Rails.root)
                                      .to_s
  else
    new_file_name = file_name
    extension = template_extension
    target_dir = "app/assets/javascripts/components"
  end

  file_path = File.join(target_dir, class_path, "#{new_file_name}.#{extension}")
  template("component.#{template_extension}", file_path)
end