fast_jsonapi icon indicating copy to clipboard operation
fast_jsonapi copied to clipboard

Add support for a conditional block (feature request)

Open benlinton opened this issue 6 years ago • 5 comments

I'd like to do something like this,

conditional_block, if: Proc.new { ... } do
  attribute :foo
  attributes :baz, baa
  has_many :bars
end

Instead of defining the same Proc many many times on optional attributes and associations.

benlinton avatar Sep 10 '18 15:09 benlinton

Could you elaborate more about what are the use cases when you would need this functionality?

shishirmk avatar Sep 15 '18 17:09 shishirmk

@shishirmk how about situation when some of the attributes are not needed when collection is serialized but there are necessary when only one object is serialized ?

On the other hand if some of the attribute is conditional and requires also small modification (eg. created_at -> format date before returning it ).

It would be easier with such conditional_block IMO or maybe I am missing some existing functionality which allow to do it right now.

jakubmank avatar Sep 27 '18 15:09 jakubmank

@jakubmank if you want to just format the date differently there are options today for that

  attribute :name do |object, params|
    "#{object.created_at.to_format(params[:format])}"
  end

shishirmk avatar Nov 05 '18 01:11 shishirmk

Hi All - To elaborate on this, I just ran into a similar issue. I basically have several attributes that I'd like to format and then serialize based on certain conditions.

For example, in the model I'm computing several properties such as total sales, total refunds, and total revenue. When those numbers equal 0 they get serialized as an integer whereas when they have a value such as 1000.00 they get serialized as a string. I need to serialize both scenarios as a string for the front-end client.

At the same time, I don't want to return those values in the serialized response when a certain parameter is present on the fetch: params[:index] != true. That way, I can save on some server computations when the client's fetching an index of resources as opposed to a single resource.

I realize I could create a separate serializer for this but it'd be nice if I could combine formatting and a conditional on an attribute in the serializer. Just my two cents :)

ehubbell avatar Feb 06 '19 17:02 ehubbell

At the same time, I don't want to return those values in the serialized response when a certain parameter is present on the fetch: params[:index] != true.

@ehubbell Not sure if this helps, but you should be able to do something like the following:

attribute :name, if: Proc.new { |_, params| params[:index] != true } do |object, params|
  ...
end

Though of course, you have to do this individually for every attribute.

tugayac avatar Mar 04 '19 16:03 tugayac