class RailsUpgrader::StrongParams

Constants

ATTR_ACCESSIBLES

Attributes

controller_path[R]
entity[R]
model_path[R]
param_key[R]

Public Class Methods

new(entity) click to toggle source
# File lib/rails_upgrader/strong_params.rb, line 8
def initialize(entity)
  @entity = entity
  @param_key = ActiveModel::Naming.param_key(entity.model)
  @controller_path = "app/controllers/#{param_key}s_controller.rb"
  @model_path = "app/models/#{param_key}.rb"
end

Public Instance Methods

already_upgraded?() click to toggle source
# File lib/rails_upgrader/strong_params.rb, line 15
def already_upgraded?
  controller_content.include?("def #{param_key}_params")
end
update_controller_content!() click to toggle source
# File lib/rails_upgrader/strong_params.rb, line 19
def update_controller_content!
  updated_content = appended_strong_params

  File.open(controller_path, 'wb') do |file|
    file.write(updated_content)
  end
end
update_model_content!() click to toggle source
# File lib/rails_upgrader/strong_params.rb, line 27
def update_model_content!
  updated_content = removed_attr_accessible

  File.open(model_path, 'wb') do |file|
    file.write(updated_content)
  end
end

Private Instance Methods

appended_strong_params() click to toggle source
# File lib/rails_upgrader/strong_params.rb, line 37
def appended_strong_params
  result = controller_content
  last_end = controller_content.rindex("end")
  result[last_end..last_end+3] = "\n#{generate_method}end\n"
  result
end
controller_content() click to toggle source
# File lib/rails_upgrader/strong_params.rb, line 50
def controller_content
  File.read(controller_path)
end
generate_method() click to toggle source
# File lib/rails_upgrader/strong_params.rb, line 58
def generate_method
  result = "  def #{param_key}_params\n"
  result += "    params.require(:#{param_key})\n"

  param_list = entity.attributes.reject do |attribute|
    attribute.to_s =~ /^id$|^type$|^created_at$|^updated_at$|_token$|_count$/
  end.map { |attribute| ":#{attribute}" }.join(", ")
  result += "          .permit(#{param_list})\n"

  if entity.model.nested_attributes_options.present?
    result += "  # TODO: check nested attributes for: #{entity.model.nested_attributes_options.keys.join(', ')}\n"
  end
  result += "  end\n\n"
  result
end
model_content() click to toggle source
# File lib/rails_upgrader/strong_params.rb, line 54
def model_content
  File.read(model_path)
end
removed_attr_accessible() click to toggle source
# File lib/rails_upgrader/strong_params.rb, line 44
def removed_attr_accessible
  result = model_content
  result[ATTR_ACCESSIBLES] = "\n"
  result
end