toptal / chewy

High-level Elasticsearch Ruby framework based on the official elasticsearch-ruby client
MIT License
1.88k stars 366 forks source link

Update crutch.rb to allow crutch inter-dependency with efficiency #965

Open akshay58538 opened 1 week ago

akshay58538 commented 1 week ago

Adds support for passing all crutches into a crutch definition, to be able to form a chain of crutches such that a field can depend and load only what it needs, instead of loading multiple objects at times, which might not all be required always.

Earlier:

class MyIndex

    crutch :my_large_crutch do |models|
        model_rel1_ids = models.map { |m| m.rel1_id }
        rel1_objs = <Load objects of Rel1 from Mongo>
        rel2_ids = rel1_objs.map{ |r| r.rel2_id }
        rel2_objs  = <Load objects of Rel2 from Mongo>
        ..... Relations can go any nested levels
        data = {}
        data[:rel1_objs] = <hash_of rel1_objs>
        data[:rel2_objs] = <hash_of rel2_objs>
        data
    end

    field :field_belongs_to_rel1_obj # <also ends up loading rel2 objects in case of partial update>
    field :field_belongs_to_rel2_obj
end

Now:

class MyIndex

    crutch :my_rel1_objs do |models|
         model_rel1_ids = models.map { |m| m.rel1_id }
        rel1_objs = <Load objects of Rel1 from Mongo>
        <hash of rel1_objs>
    end

    crutch :my_rel2_objs do |_, crutches|
         rel1_objs = crutches.my_rel1_objs
         rel2_ids = rel1_objs.map{ |r| r.rel2_id }
        rel2_objs  = <Load objects of Rel2 from Mongo>
        <hash of rel2_objs>
    end

    field :field_belongs_to_rel1_obj # <now can depend only on my_rel1_objs crutch, avoiding loading of rel2 objects, in case of a partial update>
    field :field_belongs_to_rel2_obj
end

Before submitting the PR make sure the following are checked: