Tag: extension

Extending ActiveRecord association to cleanup your associations code

For some reason not many RoR developers know that they can extend ActiveRecord associations. This feature can be a great way to cleanup any relational code that is dependent on a parent resource (or to just add a simple functionalities to scopes). Here's a really simple example how you can use it:

class User < ActiveRecord::Base
  module GroupActions
    # Here you work on a scope
    def reactivate!
      # I know we could use update_all - this is not the case ;)
      map(&:reactivate!)
    end
  end

  belongs_to :group

  def reactivate!
    update!(active: true)
  end
end

class Group < ActiveRecord::Base
  has_many :users, extend: User::GroupActions
end

That way you can perform actions like this one:

# Looks much better than any method like current_group.reactivate_users!
current_group.users.reactivate!

Dynamic pagination (changeable per page on a parent resource)

You can also use a small trick to access parent model and it's data. It can be useful for example when implementing a dynamic pagination model (based on a parent key value) or any other functionality that somehow depends on a relation owning model. Instead of doing something like this in your controllers:

def index
  @pictures = current_gallery.pictures.per(current_gallery.per_page).page(current_page)
end

you can leave the implementation details out of it (which in general is a good idea):

def index
  @pictures = current_gallery.pictures.paginated(current_page)
end

And this is how you can achieve such a behavior:

class Gallery < ActiveRecord::Base
  has_many :pictures,
    extend: Picture::RelationExtensions

  validates :per_page,
    numericality: { only_integer: true },
    inclusion: { in: (1..100).to_a }
end

class Picture < ActiveRecord::Base
  module RelationExtensions
    def paginated(current_page)
      # We create a picture instance that has a gallery reference already
      # because in the controller - gallery is a current scope starting point
      page(current_page).per(self.new.gallery.per_page)
    end
  end

  belongs_to :gallery, inverse_of:  :pictures
end

It's a really great idea to use approach like this also because you can use it with any standard scope:

current_gallery.active.paginated(current_page)
# or if you return an active record association you can chain methods
current_gallery.active.paginated(current_page).reactivate!

Conclusion

If you want to hide implementation details of any association related action (especially when it uses owning model fields data), using ActiveRecord association can be a really good idea.

Paperclip, interpolations (interpolacje) i zmiany nazwy plików

Wstęp

Są sytuacje w których chcemy aby nasze pliki z Paperclipa miały konkretne nazwy. Np. takie odpowiadające nazwom obiektów do których są dopięte (np po atrybucie name). Dla leniwych - gotowy kod na githubie.

Interpolacje

Paperclip daje nam taką możliwość dzięki interpolacjom. Możemy w bardzo prosty sposób tworzyć własne reguły nazewnictwa. Aby tego dokonać, modyfikujemy (lub tworzymy jeśli go nie mamy) plik config/initializers/paperclip_extensions.rb wpisując w nim (przykładowo):

Paperclip.interpolates :instance_name do |attachment, style|
  attachment.instance.name.to_url
end

gdzie metoda to_url (opisana tutaj) zamienia tekst na jego odpowiednik w formie nadającej się do linków (a także na nazwy plików, katalogów, itp). Przykładowo z nazwy "Przykładowa nazwa" powstanie "przykladowa-nazwa". Dzięki temu, możemy sobie poskładać nazwę dla pliku w modelu w taki oto sposób:

  has_attached_file :photo,
    :url => "/images/photos/:instance_name_:style.:extension"

Pozwala nam to tworzyć ładniejsze linki do obrazków.

Interpolacja po parametrach == problem

Interpolując z pomocą parametrów, nazwijmy to "zmiennych", pojawia się nam pewien problem. Paperclip nie zmienia samoczynnie nazw plików już utworzonych, tak więc zmieni ścieżki do plików w bazie, nie zmieniając położenia (bądź nazw) samych plików. W skutek tego jeśli utworzymy sobie model z polem :name, po którym interpolujemy, a następnie zaktualizujemy wartość tego pola, utracimy dostęp do plików będących już na serwerze. Przykładowo:

  1. Mamy model z polem :name oraz plikiem :image
  2. Interpolujemy nazwę pliku po atrybucie :name: 'images/:instance_name.:extension'
  3. Tworzymy obiekt, przypisując name => "Susanoo", dołączamy zdjęcie
  4. Otrzymujemy obiekt ze ścieżką do pliku => "images/susanoo.jpg"
  5. Aktualizujemy nazwę w naszym obiekcie, zmieniając ją na "Nokogiri". Paperclip zmieni scieżkę w bazie, na "images/nokogiri.jpg", jednak nie zmieni nazw plików, przez co w systemie plików dalej będzie plik "images/susanoo.jpg", zamiast "images/nokogiri.jpg"

Rozwiązanie - has_interpolated_attached_file

Rozwiązaniem takiej sytuacji jest wykorzystanie callbacków z ActiveRecord. Musimy "przechwycić'' stary (poprawny) adres pliku na serwerze a następnie przenieść go pod nowy adres. Musimy także zachować transakcyjność. Aby tego dokonać wykorzystamy trzy callbacki:

  1. before_update - zapamiętamy w nim nasz "stary", poprawny adres pliku - dla każdego ze stylów.
  2. after_update - mając stare nazwy oraz nowe (bo już po aktualizacji), w tym callbacku przeniesiemy pliki pod nowe adresy
  3. after_rollback - gdyby coś poszło nie tak, wycofamy zmiany wprowadzone w plikach tak aby odzyskały swoje pierwotne położenie

Całość zamkniemy w metodzie która będzie rozszerzeniem do Paperclipa, dzięki czemu będziemy mogli z niej korzystać zamiast standardowego has_attached_file.

before_update

Najpierw before_update. Tutaj sprawa jest prosta. Tworzymy sobie zmienną instancyjną która będzie hashem przechowującym. oryginalne nazwy plików (dla wszystkich styli jeśli są). Cała sztuczka polega na tym, że aby uzyskać dostęp do pierwotnych nazw. musimy odpytać bazę danych o samych siebie ale z bazy - tak żeby mieć te "poprzednie" ścieżki z nazwami. Reszta to już tylko iteracja po wartościach i przypisanie do hasha:

      before_update do |record|
        @interpolated_names = {} unless @interpolated_names
        @interpolated_names[name] = {} unless @interpolated_names[name]
        old_record = self.class.find(record.id)
        (record.send(name).styles.keys+[:original]).each do |style|
          @interpolated_names[name][style] = old_record.send(name).path(style)
        end
      end

after_update

Mamy już potrzebne nam stare i nowe ścieżki. Nie pozostaje nam nic innego, jak je pozamieniać:

      after_update do |record|
        (record.send(name).styles.keys+[:original]).each do |style|
          orig_path = @interpolated_names[name][style]
          dest_path = record.send(name).path(style)
          if orig_path && dest_path && File.exist?(orig_path) && orig_path != dest_path
            FileUtils.move(orig_path, dest_path)
          end
        end
      end

after_rollback

Dla pewności, musimy zapewnić sobie także możliwość odwrócenia zmian. Jak to zrobić? Po prostu pozamieniamy nazwy plików z powrotem, wracając do punktu wyjścia:

      after_rollback do |record|
        return unless @interpolated_names
        (record.send(name).styles.keys+[:original]).each do |style|
          dest_path = @interpolated_names[name][style]
          orig_path = record.send(name).path(style)
          if orig_path && dest_path && File.exist?(orig_path) && orig_path != dest_path
            FileUtils.move(orig_path, dest_path)
          end
        end
      end

Całość

Całość zamkniemy w metodzie has_interpolated_attached_file. Dodając do niej przy okazji oryginalny has_attached_file, co pozwoli nam korzystać z naszej metody zamiast has_attached_file:

require 'fileutils'
# Some usefull paperclip extensions
module Paperclip
  module ClassMethods

    def has_interpolated_attached_file name, options = {}

      # Get old pathes to all files from file and save in instance variable
      before_update do |record|
        @interpolated_names = {} unless @interpolated_names
        @interpolated_names[name] = {} unless @interpolated_names[name]
        old_record = self.class.find(record.id)
        (record.send(name).styles.keys+[:original]).each do |style|
          @interpolated_names[name][style] = old_record.send(name).path(style)
        end
      end

      # If validation has been passed - move files to a new location
      after_update do |record|
        (record.send(name).styles.keys+[:original]).each do |style|
          orig_path = @interpolated_names[name][style]
          dest_path = record.send(name).path(style)
          if orig_path && dest_path && File.exist?(orig_path) && orig_path != dest_path
            FileUtils.move(orig_path, dest_path)
          end
        end
      end

      # If renaming (or other callbacks) went wrong - restore old names to files
      after_rollback do |record|
        return unless @interpolated_names
        (record.send(name).styles.keys+[:original]).each do |style|
          dest_path = @interpolated_names[name][style]
          orig_path = record.send(name).path(style)
          if orig_path && dest_path && File.exist?(orig_path) && orig_path != dest_path
            FileUtils.move(orig_path, dest_path)
          end
        end
      end

      has_attached_file name, options
    end

  end
end

Źródełka dostępne na moim Githubie.

Copyright © 2024 Closer to Code

Theme by Anders NorenUp ↑