module SwiftModels

Public Class Methods

classified_sort(cols) click to toggle source
# File lib/rails_to_swift/swift_models.rb, line 137
def classified_sort(cols)
  rest_cols = []
  timestamps = []
  associations = []
  id = nil

  cols = cols.each do |c|
    if c.name.eql?("id")
      id = c
    # elsif (c.name.eql?("created_at") || c.name.eql?("updated_at"))
    #   timestamps << c
    # elsif c.name[-3,3].eql?("_id")
    #   associations << c
    else
      rest_cols << c
    end
  end
  [rest_cols].each {|a| a.sort_by!(&:name) }

  return ([id] << rest_cols << timestamps).flatten
end
create_model_file(file, options) click to toggle source
# File lib/rails_to_swift/swift_models.rb, line 31
def create_model_file(file, options)
  begin
    # return false if (/# -\*- SkipSchemaAnnotations.*/ =~ (File.exist?(file) ? File.read(file) : '') )
    klass = get_model_class(file)
    if klass && klass < ActiveRecord::Base && !klass.abstract_class? && klass.table_exists?
      
      @class_name = klass.to_s
      cols = klass.columns
      cols = cols.sort_by(&:name) if(options[:sort])
      cols = classified_sort(cols) if(options[:classified_sort])
      @columns = []
      cols.each do |col|
        col_info = SwiftColumn.new
        col_info.not_null = col.null ? false : true
        col_info.type = (col.type || col.sql_type).to_s
        col_info.name = col.name
        @columns.push(col_info)
      end
      template = File.read(File.expand_path('../templates/model.swift', __FILE__))
      File.open(Rails.root.join('rails_to_swift', 'models', "#{@class_name}.swift"), "w") do |file|
        file.write ERB.new(template, nil, '>').result(binding)
      end
      # File.open(Rails.root.join('rails_to_swift', 'models', "#{@class_name}.swift"), "w") do |file|
      #   file.write Slim::Template.new({default_tag: "", use_html_safe: false, disable_escape: true}) {template}.render(binding)
      # end

    end
  rescue Exception => e
    puts "Unable to create #{file}: #{e.message}"
    puts "\t" + e.backtrace.join("\n\t") if options[:trace]
  end
end
create_model_files(options = {}) click to toggle source
# File lib/rails_to_swift/swift_models.rb, line 20
def create_model_files(options = {})
  FileUtils::mkdir_p(Rails.root.join('rails_to_swift', 'models'))
  constants_file = File.read(File.expand_path('../templates/Constants.swift', __FILE__))
  nsdate_file = File.read(File.expand_path('../templates/NSDate+Rails.swift', __FILE__))
  File.open(Rails.root.join('rails_to_swift', "Constants.swift"), 'w') {|f| f.write(constants_file) }
  File.open(Rails.root.join('rails_to_swift', "NSDate+Rails.swift"), 'w') {|f| f.write(nsdate_file) }
  get_model_files(options).each do |file|
    create_model_file(File.join(file), options)
  end
end
get_loaded_model(model_path) click to toggle source

Retrieve loaded model class by path to the file where it’s supposed to be defined.

# File lib/rails_to_swift/swift_models.rb, line 121
def get_loaded_model(model_path)
  begin
    ActiveSupport::Inflector.constantize(ActiveSupport::Inflector.camelize(model_path))
  rescue
    # Revert to the old way but it is not really robust
    ObjectSpace.each_object(::Class).
      select do |c|
        Class === c and    # note: we use === to avoid a bug in activesupport 2.3.14 OptionMerger vs. is_a?
        c.ancestors.respond_to?(:include?) and  # to fix FactoryGirl bug, see https://github.com/ctran/annotate_models/pull/82
        c.ancestors.include?(ActiveRecord::Base)
      end.
      detect { |c| ActiveSupport::Inflector.underscore(c.to_s) == model_path }
  end
end
get_model_class(file) click to toggle source

Retrieve the classes belonging to the model names we’re asked to process Check for namespaced models in subdirectories as well as models in subdirectories without namespacing.

# File lib/rails_to_swift/swift_models.rb, line 101
def get_model_class(file)
  model_path = file.gsub(/\.rb$/, '')
  model_dir.each { |dir| model_path = model_path.gsub(/^#{dir}/, '').gsub(/^\//, '') }
  begin
    get_loaded_model(model_path) or raise LoadError.new("cannot load a model from #{file}")
  rescue LoadError
    # this is for non-rails projects, which don't get Rails auto-require magic
    file_path = File.expand_path(file)
    if File.file?(file_path) && Kernel.require(file_path)
      retry
    elsif model_path.match(/\//)
      model_path = model_path.split('/')[1..-1].join('/').to_s
      retry
    else
      raise
    end
  end
end
get_model_files(options) click to toggle source

Return a list of the model files to annotate. If we have command line arguments, they’re assumed to the path of model files from root dir. Otherwise we take all the model files in the model_dir directory.

# File lib/rails_to_swift/swift_models.rb, line 68
def get_model_files(options)
  models = []
  if(!options[:is_rake])
    models = ARGV.dup.reject{|m| m.match(/^(.*)=/)}
  end

  if models.empty?
    begin
      model_dir.each do |dir|
        Dir.chdir(dir) do
          lst =
            if options[:ignore_model_sub_dir]
              Dir["*.rb"].map{ |f| [dir, f] }
            else
              Dir["**/*.rb"].reject{ |f| f["concerns/"] }.map{ |f| [dir, f] }
            end
          models.concat(lst)
        end
      end
    rescue SystemCallError
      puts "No models found in directory '#{model_dir.join("', '")}'."
      puts "Either specify models on the command line, or use the --model-dir option."
      puts "Call 'annotate --help' for more info."
      exit 1
    end
  end

  models
end
model_dir() click to toggle source
# File lib/rails_to_swift/swift_models.rb, line 8
def model_dir
  @model_dir.is_a?(Array) ? @model_dir : [@model_dir || "app/models"]
end
model_dir=(dir) click to toggle source
# File lib/rails_to_swift/swift_models.rb, line 12
def model_dir=(dir)
  @model_dir = dir
end
schema_default(klass, column) click to toggle source
# File lib/rails_to_swift/swift_models.rb, line 16
def schema_default(klass, column)
  quote(klass.column_defaults[column.name])
end