Paul
Paul

Reputation: 26660

Ruby: Working in context of some namespace

Here is a piece of code which uses enum many times:

.where("items.state in (#{Workflow::ItemStatus::MOVING},#{Workflow::ItemStatus::WAITING},#{Workflow::ItemStatus::EXECUTING},#{Workflow::ItemStatus::ASSIGNED})")

What I do not like is the Workflow::ItemStatus namespace repeated many times which produces a long string.

I would like to wrap code in some construction which will allow me to do:

.where("items.state in (#{[MOVING, WAITING, EXECUTING, ASSIGNED].join(',')})")

Upvotes: 0

Views: 37

Answers (2)

Paul
Paul

Reputation: 26660

I worked for myself a compromise solution out:

st = Workflow::ItemStatus
Item.joins(.....).where("items.state in (#{st::MOVING},#{st::WAITING},#{st::EXECUTING},#{st::ASSIGNED})")

Upvotes: 0

Arup Rakshit
Arup Rakshit

Reputation: 118271

You can write

constants = %i(MOVING WAITING EXECUTING ASSIGNED)
.where("items.state in (?)", constants.map { |c| Workflow::ItemStatus.const_get(c) })

Upvotes: 1

Related Questions