Sha256: d6ab179ef0619f52d87da205ced5b2e205c24924ddb270ee944776d4c018a4a5

Contents?: true

Size: 935 Bytes

Versions: 10

Compression:

Stored size: 935 Bytes

Contents

# frozen_string_literal: true

module ChinaRegions
  class FetchOptionsController < ::ActionController::Metal
    def index
      if params_valid?(params) && (parent_klass = params[:parent_klass].classify.safe_constantize.find(params[:parent_id]))
        table_name = params[:klass].tableize
        regions = parent_klass.__send__(table_name).select("#{table_name}.id, #{table_name}.name")
        regions = if level_column?(params[:klass])
          regions.order('level ASC')
        else
          regions.order('name ASC')
        end
      else
        regions = []
      end

      self.response_body = regions.to_json
    end

    protected

    def level_column?(klass_name)
      klass_name.classify.safe_constantize.try(:column_names).to_a.include?('level')
    end

    def params_valid?(params)
      params[:klass].present? && params[:parent_klass] =~ /^province|city$/i && params[:parent_id].present?
    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
china_regions-1.0.8 app/controllers/china_regions/fetch_options_controller.rb
china_regions-1.0.7 app/controllers/china_regions/fetch_options_controller.rb
china_regions-1.0.5 app/controllers/china_regions/fetch_options_controller.rb
china_regions-1.0.4 app/controllers/china_regions/fetch_options_controller.rb
china_regions-1.0.3 app/controllers/china_regions/fetch_options_controller.rb
china_regions-1.0.2 app/controllers/china_regions/fetch_options_controller.rb
china_regions-1.0.1 app/controllers/china_regions/fetch_options_controller.rb
china_regions-1.0.0 app/controllers/china_regions/fetch_options_controller.rb
china_regions-0.4.5 app/controllers/china_regions/fetch_options_controller.rb
china_regions-0.4.4 app/controllers/china_regions/fetch_options_controller.rb