Skip to content

Instantly share code, notes, and snippets.

@SandNerd
Last active September 17, 2016 01:35
Show Gist options
  • Save SandNerd/0547e93ad87c8e65eaef309e8e7ffee1 to your computer and use it in GitHub Desktop.
Save SandNerd/0547e93ad87c8e65eaef309e8e7ffee1 to your computer and use it in GitHub Desktop.
Ruby Gems Manipulation

Ruby Gems Manipulation

"hmm, so they didn't give you a decent api to make the changes you need.."

"Can't touch this"

Methods

Removing

undef_method

  • Deletes the method entirely #=> NoMethodError
  • Shoud be used with an if defined? statement

remove_method

  • Prevents current class from responding to the method #=> nil
  • Shoud be used with an if method_defined? statement

For example

num = Number.new
num << 4 #=> [4]
num.include? #=> "Just kidding"
Number.class_eval("remove_method :include?")
num.include? 4 #=> true
Number.class_eval("undef include?")
num.include? 4 #=> NoMethodError

Removing Aliases

alias_method :fake?, :original?

can be removed with

remove_method :fake?

However, if alias_method overwrites an existing method

# assuming :original? is already a method
alias_method :fake?, :original?
alias_method :original?, :temproary_original?

To restore the first state:

alias_method :original?, :fake?
remove_method :fake?  # optional

Rails Related

Validations

Skipping All Validations

It's possible to skip validations with

@dummy.save_without_validation

Removing All Validations

To remove all validations:

clear_validators!

Removing Specific Validation

E.g.

validates :zzzzz, presence: true

Can be removed with

  _validators[:zzzzz]
    .find { |v| v.is_a? ActiveRecord::Validations::PresenceValidator }
    .attributes
    .delete(:zzzzz)

Model Callbacks

Removing Specific Callbacks

# remove `Model.`
Model.skip_callback(:destroy, :before, :check_if_admin), :prepend => :true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment