Skip to content

Commit

Permalink
bump version
Browse files Browse the repository at this point in the history
  • Loading branch information
emfy0 committed Sep 17, 2024
1 parent 2718b8c commit fac79fc
Show file tree
Hide file tree
Showing 4 changed files with 6 additions and 12 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ virtual_field :virtual_attribute,
Parameters:
- `name`: The name of the virtual field.
- `scope`: A lambda defining a scope that fetches the virtual field value (optional).
- `select`: SQL selection logic (can be a string or a lambda returning an SQL string) to define how the field is computed.
- `select`: SQL selection logic (can be a `string | arel_node` or a lambda returning an SQL `string | arel_node`) to define how the field is computed.
- `get`: A method to retrieve the value of the virtual field when the field isn't fetched via SQL.
- `default`: A default value for the virtual field if the result is nil.

Expand Down
Binary file added ar_virtual_field.gem
Binary file not shown.
14 changes: 4 additions & 10 deletions lib/ar_virtual_field.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ def self.select_append(relation, *values)
end
end

def virtual_field(name, scope:, select: nil, get:, default:)
def virtual_field(name, scope: nil, select:, get:, default:)
name = name.to_s
current_class = self
unwrap_arel_expression = -> (exp) { exp.is_a?(Arel::Nodes::NodeExpression) ? exp : Arel.sql(exp) }
Expand All @@ -31,15 +31,9 @@ def virtual_field(name, scope:, select: nil, get:, default:)
scope(scope_name, scope)

scope(:"with_#{name}", -> do
scope_query = current_class.send(scope_name)

if scope_query.group_values.present?
scope_query = scope_query.reselect(select_lambda.().as(name), "#{table_name}.id")
new_scope = joins("LEFT JOIN (#{scope_query.to_sql}) #{name}_outer ON #{name}_outer.id = #{table_name}.id")
HelperMethods.select_append(new_scope, "#{name}_outer.#{name} AS #{name}")
else
HelperMethods.select_append(send(scope_name), select_lambda.().as(name))
end
scope_query = current_class.send(scope_name).select(select_lambda.().as(name), "#{table_name}.id")
new_scope = joins("LEFT JOIN (#{scope_query.to_sql}) #{name}_outer ON #{name}_outer.id = #{table_name}.id")
HelperMethods.select_append(new_scope, "#{name}_outer.#{name} AS #{name}")
end)
else
scope(:"with_#{name}", -> do
Expand Down
2 changes: 1 addition & 1 deletion lib/ar_virtual_field/version.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# frozen_string_literal: true

module ArVirtualField
VERSION = "0.1.0"
VERSION = "0.3.0"
end

0 comments on commit fac79fc

Please sign in to comment.