8 Matching Annotations
  1. Aug 2023
    1. I make a file named: app/models/active_storage/attachment.rb. Because it's in your project it takes loading precedence over the Gem version. Then inside we load the Gem version, and then monkeypatch it using class_eval: active_storage_gem_path = Gem::Specification.find_by_name('activestorage').gem_dir require "#{active_storage_gem_path}/app/models/active_storage/attachment" ActiveStorage::Attachment.class_eval do acts_as_taggable on: :tags end The slightly nasty part is locating the original file, since we can't find it normally because our new file takes precedence. This is not necessary in production, so you could put a if Rails.env.production? around it if you like I think.
  2. Mar 2023
  3. Jul 2022
    1. Create a new controller to override the original: app/controllers/active_storage/blobs_controller.rb

      Original comment:

      I've never seen monkey patching done quite like this.

      Usually you can't just "override" a class. You can only reopen it. You can't change its superclass. (If you needed to, you'd have to remove the old constant first.)

      Rails has already defined ActiveStorage::BlobsController!

      I believe the only reason this works:

      class ActiveStorage::BlobsController < ActiveStorage::BaseController

      is because it's reopening the existing class. We don't even need to specify the < Base class. (We can't change it, in any case.)

      They do the same thing here: - https://github.com/ackama/rails-template/pull/284/files#diff-2688f6f31a499b82cb87617d6643a0a5277dc14f35f15535fd27ef80a68da520

      Correction: I guess this doesn't actually monkey patch it. I guess it really does override the original from activestorage gem and prevent it from getting loaded. How does it do that? I'm guessing it's because activestorage relies on autoloading constants, and when the constant ActiveStorage::BlobsController is first encountered/referenced, autoloading looks in paths in a certain order, and finds the version in the app's app/controllers/active_storage/blobs_controller.rb before it ever gets a chance to look in the gem's paths for that same path/file.

      If instead of using autoloading, it had used require_relative (or even require?? but that might have still found the app-defined version earlier in the load path), then it would have loaded the model from activestorage first, and then (possibly) loaded the model from our app, which (probably) would have reopened it, as I originally commented.

  4. Nov 2021
    1. you can define locally parse and it should take precedence over the one in the library: interface JSON { parse(text: string, reviver?: (key: any, value: any) => any): unknown; }
  5. Nov 2020
  6. Dec 2019
  7. Oct 2019
    1. If you're given a set of factories (say, from a gem developer) but want to change them to fit into your application better, you can modify that factory instead of creating a child factory and adding attributes there.