BWeave Ramblings, maybe, when I get around to it.

ActiveRecord::Observer

TIL ActiveRecord::Observer is a thing. You can use it to pull AR model callbacks out into dedicated classes. This seems useful if you’ve got a handful(s) of related callbacks and need a better way to organize them.

class PostObserver < ActiveRecord::Observer
  def after_create(post)
    Subscribers.send_new_post_notification(post)
  end
end

class CommentObserver < ActiveRecord::Observer
  def after_create(comment)
    Subscribers.send_new_comment_notification(comment)
  end
end

As you might’ve guessed, the class to observe is inferred, so in the case where it can’t be inferred, or multiple classes should be watched, do this.

class AuditObserver < ActiveRecord::Observer
  observe :account, :balance

  def after_update(record)
    AuditTrail.new(record, "UPDATED")
  end
end

Use TTYToolkit.org to build Ruby CLI apps

Use TTYToolkit.org to build Ruby CLI apps with ease. There are tons of great components, nice-to-haves, and good docs.

Keeping Rails logs slim and trim

Add this to development.rb and test.rb in config/environments/ to clean up your development and test logs daily.

config.logger = ActiveSupport::Logger.new(config.paths['log'].first, "daily")

Check out the docs for more info.

Easily count occurences in an Array

Counting occurrence in an Array is ezpz with reduce and Hash.new(0).

%w[dog cat dog dog].reduce(Hash.new(0)) do |pet, hash|
  hash[pet] += 1
end
 => {"dog"=>3, "cat"=>1}

Count takes a block

Ruby and Crystal’s #count can both take a block and return the number of elements in the collection where the block returns true.

[1, 2, 3].count { |num| num > 2 }
#=> 1

Count the differences between two strings:

string_a = "ABC"
string_b = "CDE"
string_a.chars.zip(string_b.chars).count { |(a, b)| a != b }
#=> 4