How do I use the parser gem to extract this code snippet I want?

喜欢而已 提交于 2019-12-12 18:04:02

问题


I just stumbled across this Parser gem.

What I want to do is extract a specific method from a long file.

One example is this has_many method from Rails:

 def has_many(name, scope = nil, options = {}, &extension)
    reflection = Builder::HasMany.build(self, name, scope, options, &extension)
    Reflection.add_reflection self, name, reflection
  end

The only issue is, I need to be able to also extract another version of that same method (from an earlier time), that is more verbose and complex. That version looks like this:

def has_many(association_id, options = {})
    validate_options([ :foreign_key, :class_name, :exclusively_dependent, :dependent, :conditions, :order, :finder_sql ], options.keys)
    association_name, association_class_name, association_class_primary_key_name =
          associate_identification(association_id, options[:class_name], options[:foreign_key])

    require_association_class(association_class_name)

    if options[:dependent] and options[:exclusively_dependent]
      raise ArgumentError, ':dependent and :exclusively_dependent are mutually exclusive options.  You may specify one or the other.' # ' ruby-mode
    elsif options[:dependent]
      module_eval "before_destroy '#{association_name}.each { |o| o.destroy }'"
    elsif options[:exclusively_dependent]
      module_eval "before_destroy { |record| #{association_class_name}.delete_all(%(#{association_class_primary_key_name} = '\#{record.id}')) }"
    end

    define_method(association_name) do |*params|
      force_reload = params.first unless params.empty?
      association = instance_variable_get("@#{association_name}")
      if association.nil?
        association = HasManyAssociation.new(self,
          association_name, association_class_name,
          association_class_primary_key_name, options)
        instance_variable_set("@#{association_name}", association)
      end
      association.reload if force_reload
      association
    end

    # deprecated api
    deprecated_collection_count_method(association_name)
    deprecated_add_association_relation(association_name)
    deprecated_remove_association_relation(association_name)
    deprecated_has_collection_method(association_name)
    deprecated_find_in_collection_method(association_name)
    deprecated_find_all_in_collection_method(association_name)
    deprecated_create_method(association_name)
    deprecated_build_method(association_name)
  end

So how do I successfully extract both of those methods, using that gem?

The ReadMe for the Gem is not very friendly to complete parsing-noobs.

来源:https://stackoverflow.com/questions/38630553/how-do-i-use-the-parser-gem-to-extract-this-code-snippet-i-want

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!