Search code examples
ruby-on-rails-5rails-generators

Override rails generator to change date_select into date_field


I have been trying to override the rails generator (when you run rails generate scaffold) to produce for a date type a date_field instead of date_select in the form (same for time and date time). The mapping is located in railties/lib/rails/generators/generated_attribute.rb

def field_type @field_type ||= case type when :integer then :number_field when :float, :decimal then :text_field when :time then :time_select when :datetime, :timestamp then :datetime_select when :date then :date_select when :text then :text_area when :boolean then :check_box else :text_field end end

I can't work out where to put the updated generated_attribute.rb file. I have tried in the rails app lib/generators/generated_attribute.rb and lib/templates/generators/generated_attribute.rb to no effect. I have not found any other information about overriding this file to change the behaviour.

Thanks in advance. Using rails 5.2


Solution

  • It looks like there is no automatic overriding of this file yet. I've put mine at lib/rails/generators/generated_attribute.rb Then you can add require "#{Rails.root}/lib/rails/generators/generated_attribute.rb" on top on your overriden lib/rails/generators/erb/scaffold/scaffold_generator.rb:

    require "#{Rails.root}/lib/rails/generators/generated_attribute.rb"
    require "rails/generators/erb"
    require "rails/generators/resource_helpers"
    
    module Erb # :nodoc:
      module Generators # :nodoc:
        class ScaffoldGenerator < Base # :nodoc:
    

    A bit dirty, but I hope this helps.