Class: ScaffoldPlus::Generators::GeodesicGenerator

Inherits:
ActiveRecord::Generators::Base
  • Object
show all
Defined in:
lib/generators/scaffold_plus/geodesic/geodesic_generator.rb

Instance Method Summary collapse

Instance Method Details

#add_migrationObject



25
26
27
28
# File 'lib/generators/scaffold_plus/geodesic/geodesic_generator.rb', line 25

def add_migration
  return unless options.migration?
  migration_template 'geodesic_migration.rb', "db/migrate/#{migration_name}.rb"
end

#update_controllerObject



63
64
65
66
67
68
69
70
71
# File 'lib/generators/scaffold_plus/geodesic/geodesic_generator.rb', line 63

def update_controller
  return unless options.permit?
  text = ":#{options.latitude}, :#{options.longitude}"
  text << ", :address, :country" if options.address?
  file = "app/controllers/#{table_name}_controller.rb"
  gsub_file file, /(permit\(.*)\)/, "\\1, #{text})"
  # Special case: no previous permit
  gsub_file file, /^(\s*params)\[:#{name}\]$/, "\\1.require(:#{name}).permit(#{text})"
end

#update_modelObject



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/generators/scaffold_plus/geodesic/geodesic_generator.rb', line 30

def update_model
  lat = options.latitude
  lng = options.longitude
  file = "app/models/#{name}.rb"
  prepend_to_file file, "require 'geodesic_wgs84'\n\n"
  lines = options.before? ? [ "" ] : []
  lines << [
    "  def to_lat_lon",
    "    [#{lat}, #{lng}]",
    "  end",
    "",
    "  def as_dms(value)",
    "    return '' if value.blank?",
    "    wgs84 = Wgs84.new",
    "    wgs84.as_dms(value)",
    "  end",
    "",
    "  before_save on: [:create, :update] do",
    "    # Normalize geo information",
    "    wgs84 = Wgs84.new",
    "    if self.#{lat}.present?",
    "      self.#{lat} = wgs84.as_bigdec(self.#{lat})",
    "    end",
    "    if self.#{lng}.present?",
    "      self.#{lng} = wgs84.as_bigdec(self.#{lng})",
    "    end",
    "  end",
    ""
  ]
  lines << "" if options.after?
  inject_into_class file, class_name, lines.join("\n")
end