動かざることバグの如し

静かに頬を伝う涙が 私に知らせる これが初恋と

RubyKaigiのRubyDebugCheatSheetで気になったやつ

NaCl(オープンソース・フロンティア - ネットワーク応用通信研究所)さんが配ってたRubyデバッグに使えるテクニック集。

コードに書き起こしておいたほうが、コピペもしやすいと思うのでメモ

ppでオブジェクトと整形表示

メソッドがある事自体は知っていたが、require 'pp'しなくてはならず、面倒だったので殆ど使ってなかった。しかし、Ruby2.5以上ではrequireなしで呼べるようになったとのこと。どんどんつかっていこう(テノヒラクルー

require 'open-uri'
require 'json'

a = open('http://httpbin.org/json').read
b = JSON.parse a
irb(main):008:0> pp b
{"slideshow"=>
  {"author"=>"Yours Truly",
   "date"=>"date of publication",
   "slides"=>
    [{"title"=>"Wake up to WonderWidgets!", "type"=>"all"},
     {"items"=>
       ["Why <em>WonderWidgets</em> are great",
        "Who <em>buys</em> WonderWidgets"],
      "title"=>"Overview",
      "type"=>"all"}],
   "title"=>"Sample Slide Show"}}

ファイルに書き出したいときはpretty_inspectを使う

File.write('a.txt', b.pretty_inspect)

オブジェクトの素性を調べる

例えばRailsrails g scaffold taskしたあとのTaskモデルを見るとき、

> t = Task.new
=> #<Task id: nil, title: nil, deadline: nil, created_at: nil, updated_at: nil>

クラス名を表示

irb(main):007:0> t.class
=> Task(id: integer, title: string, deadline: date, created_at: datetime, updated_at: datetime)

継承しているクラス、includeしているモジュールを表示

irb(main):008:0> t.class.ancestors
=> [Task(id: integer, title: string, deadline: date, created_at: datetime, updated_at: datetime), Task::GeneratedAssociationMethods, #<ActiveRecord::AttributeMethods::GeneratedAttributeMethods:0x00007f7f6d1301c0>, ApplicationRecord(abstract), ApplicationRecord::GeneratedAssociationMethods, #<ActiveRecord::AttributeMethods::GeneratedAttributeMethods:0x00007f7f6d2017c0>, ActiveRecord::Base, GlobalID::Identification, ActiveRecord::Suppressor, ActiveRecord::SecureToken, ActiveRecord::Store, ActiveRecord::Serialization, ActiveModel::Serializers::JSON, ActiveModel::Serialization, ActiveRecord::Reflection, ActiveRecord::NoTouching, ActiveRecord::TouchLater, ActiveRecord::Transactions, ActiveRecord::Aggregations, ActiveRecord::NestedAttributes, ActiveRecord::AutosaveAssociation, ActiveModel::SecurePassword, ActiveRecord::Associations, ActiveRecord::Timestamp, ActiveRecord::Callbacks, ActiveRecord::AttributeMethods::Serialization, ActiveRecord::AttributeMethods::Dirty, ActiveModel::Dirty, ActiveRecord::AttributeMethods::TimeZoneConversion, ActiveRecord::AttributeMethods::PrimaryKey, ActiveRecord::AttributeMethods::Query, ActiveRecord::AttributeMethods::BeforeTypeCast, ActiveRecord::AttributeMethods::Write, ActiveRecord::AttributeMethods::Read, ActiveRecord::Base::GeneratedAssociationMethods, #<ActiveRecord::AttributeMethods::GeneratedAttributeMethods:0x00007f7f68bcfd10>, ActiveRecord::AttributeMethods, ActiveModel::AttributeMethods, ActiveModel::Validations::Callbacks, ActiveRecord::DefineCallbacks, ActiveRecord::Locking::Pessimistic, ActiveRecord::Locking::Optimistic, ActiveRecord::AttributeDecorators, ActiveRecord::Attributes, ActiveRecord::CounterCache, ActiveRecord::Validations, ActiveModel::Validations::HelperMethods, ActiveSupport::Callbacks, ActiveModel::Validations, ActiveRecord::Integration, ActiveModel::Conversion, ActiveRecord::AttributeAssignment, ActiveModel::AttributeAssignment, ActiveModel::ForbiddenAttributesProtection, ActiveRecord::Sanitization, ActiveRecord::Scoping::Named, ActiveRecord::Scoping::Default, ActiveRecord::Scoping, ActiveRecord::Inheritance, ActiveRecord::ModelSchema, ActiveRecord::ReadonlyAttributes, ActiveRecord::Persistence, ActiveRecord::Core, ActiveSupport::ToJsonWithActiveSupportEncoder, Object, PP::ObjectMixin, JSON::Ext::Generator::GeneratorMethods::Object, ActiveSupport::Tryable, ActiveSupport::Dependencies::Loadable, Kernel, BasicObject]

呼び出せるメソッド一覧表示

irb(main):009:0> t.public_methods
=> [:created_at, :title, :id_came_from_user?, :id_changed?, :id_change, :id_will_change!, :id_previously_changed?, :id_previous_change, :restore_id!, :saved_change_to_id?, :saved_change_to_id, :id_before_last_save, :will_save_change_to_id?, :id_change_to_be_saved, :title_before_type_cast, :title_came_from_user?, :title?, :title_changed?, :title_change, :deadline, :title_will_change!, :title_was, :title=, :restore_title!, :title_previously_changed?, :title_previous_change, :saved_change_to_title, :saved_change_to_title?, :will_save_change_to_title?, :title_before_last_save, :title_in_database, :deadline=, :deadline_before_type_cast, :deadline_came_from_user?, :deadline?, :deadline_changed?, :deadline_change, :deadline_will_change!, :deadline_was, :deadline_previously_changed?, :deadline_previous_change, :title_change_to_be_saved, :restore_deadline!, :saved_change_to_deadline?, :saved_change_to_deadline, :deadline_before_last_save, :will_save_change_to_deadline?, :deadline_change_to_be_saved, :deadline_in_database, :created_at=, :created_at_before_type_cast, :created_at_came_from_user?, :created_at?, :created_at_changed?, :created_at_change, :created_at_will_change!, :created_at_was, :created_at_previously_changed?, :created_at_previous_change, :restore_created_at!, :saved_change_to_created_at?, :saved_change_to_created_at, :created_at_before_last_save, :will_save_change_to_created_at?, :created_at_change_to_be_saved, :created_at_in_database, :updated_at=, :updated_at_before_type_cast, :updated_at_came_from_user?, :updated_at?, :updated_at_changed?, :updated_at, :updated_at_change, :updated_at_will_change!, :updated_at_was, :updated_at_previously_changed?, :updated_at_previous_change, :restore_updated_at!, :saved_change_to_updated_at?, :saved_change_to_updated_at, :updated_at_before_last_save, :will_save_change_to_updated_at?, :updated_at_change_to_be_saved, :updated_at_in_database, :model_name, :record_timestamps?, :record_timestamps=, :defined_enums, :pluralize_table_names, :_run_validation_callbacks, :__callbacks?, :index_nested_attribute_errors, :default_timezone, :_validate_callbacks, :_validators?, :_reflections, :primary_key_prefix_type, :_reflections?, :aggregate_reflections?, :include_root_in_json, :defined_enums?, :lock_optimistically, :include_root_in_json?, :verbose_query_logs, :cache_timestamp_format, :table_name_prefix, :lock_optimistically?, :schema_format, :error_on_ignored_order, :dump_schema_after_migration, :dump_schemas, :_validation_callbacks, :_initialize_callbacks, :default_connection_handler, :table_name_prefix?, :_find_callbacks, :table_name_suffix?, :_run_touch_callbacks, :_touch_callbacks, :_run_save_callbacks, :nested_attributes_options, :store_full_sti_class, :_save_callbacks, :_run_create_callbacks, :_create_callbacks, :_run_update_callbacks, :_update_callbacks, :timestamped_migrations, :column_for_attribute, :_run_initialize_callbacks, :_run_destroy_callbacks, :_run_find_callbacks, :store_full_sti_class?, :table_name_suffix, :default_scopes, :default_scope_override, :_destroy_callbacks, :attribute_aliases?, :attribute_method_matchers?, :nested_attributes_options?, :allow_unsafe_raw_sql, :time_zone_aware_attributes, :skip_time_zone_conversion_for_attributes, :time_zone_aware_types, :skip_time_zone_conversion_for_attributes?, :logger, :time_zone_aware_types?, :partial_writes, :type_for_attribute, :_run_before_commit_without_transaction_enrollment_callbacks, :default_connection_handler?, :_run_before_commit_callbacks, :_run_commit_without_transaction_enrollment_callbacks, :_run_commit_callbacks, :attribute_aliases, :attribute_method_matchers, :pluralize_table_names?, :_run_rollback_callbacks, :cache_versioning, :_run_rollback_without_transaction_enrollment_callbacks, :cache_timestamp_format?, :cache_versioning?, :partial_writes?, :validation_context, :_validators, :_commit_callbacks, :_before_commit_callbacks, :_rollback_callbacks, :__callbacks, :_run_validate_callbacks, :_before_commit_without_transaction_enrollment_callbacks, :_commit_without_transaction_enrollment_callbacks, :_rollback_without_transaction_enrollment_callbacks, :record_timestamps, :aggregate_reflections, :warn_on_records_fetched_greater_than, :to_signed_global_id, :to_sgid, :to_sgid_param, :to_global_id, :to_gid, :to_gid_param, :save, :save!, :serializable_hash, :from_json, :as_json, :read_attribute_for_serialization, :touch_later, :no_touching?, :touch, :rollback_active_record_state!, :before_committed!, :committed!, :rolledback!, :add_to_transaction, :destroy, :transaction, :with_transaction_returning_status, :reload, :_destroy, :mark_for_destruction, :destroyed_by_association=, :changed_for_autosave?, :marked_for_destruction?, :destroyed_by_association, :association, :association_cached?, :increment!, :attribute_in_database, :saved_change_to_attribute?, :saved_change_to_attribute, :attribute_before_last_save, :saved_changes?, :saved_changes, :will_save_change_to_attribute?, :attribute_change_to_be_saved, :changes_to_save, :changed_attribute_names_to_save, :attributes_in_database, :has_changes_to_save?, :changes, :changed?, :changed, :attribute_changed_in_place?, :changes_applied, :changed_attributes, :attribute_changed?, :attribute_previously_changed?, :restore_attributes, :clear_changes_information, :clear_attribute_changes, :previous_changes, :attribute_was, :id_was, :id?, :id_in_database, :id, :id=, :to_key, :id_before_type_cast, :query_attribute, :attributes_before_type_cast, :read_attribute_before_type_cast, :write_attribute, :_write_attribute, :_read_attribute, :read_attribute, :attribute_for_inspect, :attribute_present?, :accessed_fields, :[], :[]=, :attribute_names, :respond_to?, :attributes, :has_attribute?, :respond_to_without_attributes?, :attribute_missing, :method_missing, :with_lock, :lock!, :locking_enabled?, :valid?, :validate, :validates_exclusion_of, :validates_acceptance_of, :validates_confirmation_of, :validates_inclusion_of, :validates_length_of, :validates_numericality_of, :validates_size_of, :validates_format_of, :validates_absence_of, :validates_presence_of, :run_callbacks, :invalid?, :validate!, :validates_with, :read_attribute_for_validation, :errors, :cache_key, :cache_version, :to_param, :cache_key_with_version, :to_model, :to_partial_path, :assign_attributes, :attributes=, :populate_with_current_scope_attributes, :initialize_internals_callback, :update!, :update_column, :update_columns, :delete, :decrement!, :toggle, :toggle!, :persisted?, :update, :destroyed?, :destroy!, :becomes, :increment, :decrement, :becomes!, :new_record?, :update_attribute, :update_attributes, :update_attributes!, :pretty_print, :readonly?, :<=>, :readonly!, :freeze, :init_with, :==, :hash, :inspect, :connection_handler, :slice, :encode_with, :eql?, :frozen?, :to_json, :instance_values, :instance_variable_names, :`, :present?, :presence, :acts_like?, :blank?, :in?, :presence_in, :deep_dup, :to_query, :duplicable?, :with_options, :to_yaml, :html_safe?, :pretty_print_instance_variables, :pretty_print_cycle, :pretty_print_inspect, :try, :try!, :load_dependency, :unloadable, :require_or_load, :require_dependency, :instance_variable_set, :instance_variable_defined?, :remove_instance_variable, :instance_of?, :kind_of?, :is_a?, :tap, :instance_variable_get, :public_methods, :instance_variables, :method, :public_method, :define_singleton_method, :singleton_method, :public_send, :class_eval, :extend, :byebug, :remote_byebug, :debugger, :to_enum, :enum_for, :gem, :===, :=~, :!~, :object_id, :send, :to_s, :display, :pretty_inspect, :nil?, :class, :singleton_class, :clone, :dup, :yield_self, :itself, :tainted?, :taint, :untrust, :untaint, :trust, :untrusted?, :methods, :singleton_methods, :protected_methods, :private_methods, :!, :equal?, :instance_eval, :instance_exec, :!=, :__id__, :__send__]

呼び出せるメソッド一覧表示(継承したメソッドを除外)

irb(main):010:0> t.public_methods(false)
=> []

空だが、generateして特に弄ってないので当然

requireしたときに読み込まれるファイルを表示

今までgrepとかgithubで探してた。。恥ずかしい

$gem which active_record
/Users/thr3a/.rbenv/versions/2.5.1/lib/ruby/gems/2.5.0/gems/activerecord-5.2.3/lib/active_record.rb

つづく