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' => ->(type) {
    'PropTypes.instanceOf(%s)' % type.to_s.camelize
  },

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

  'oneOfType' => ->(*options) {
    types = options.map{ |k| "#{lookup(k.to_s, k.to_s)}" }.join(',')
    'PropTypes.oneOfType([%s])' % types
  }
}

Instance Method Summary collapse

Instance Method Details

#create_component_fileObject


92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/generators/react/component_generator.rb', line 92

def create_component_file
  template_extension = if options[:coffee]
    'js.jsx.coffee'
  elsif options[:es6] || webpacker?
    'es6.jsx'
  else
    'js.jsx'
  end

  # Prefer webpacker to sprockets:
  if webpacker?
    new_file_name = file_name.camelize
    extension = options[:coffee] ? 'coffee' : 'js'
    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