Bala Karthik
Bala Karthik

Reputation: 1413

Altering JSON response in rails?

I have a model named User and in many actions i am rendering the response as json. for ex while showing the user data, i am using

@user = User.find_by_id(params[:id]) render json: {data: @user}

Now i have a requirement that while responding user data i need to show only last 2 digit of the mobile number for ex) ********78, is there any way to achieve this, Because altering the response in each action will be too difficult so is there any way to write a common method for handling this situation.

Upvotes: 1

Views: 115

Answers (2)

Bala Karthik
Bala Karthik

Reputation: 1413

Finally i solved the problem by

def as_json(options = {})
  users = super
  users['mobile_number'] = "********" + users['mobile_number'].slice(8,9).last if users['mobile_number'].present?
  users
end

when i call

 render json: {data: @user.as_json}

even if @user can contain collection of record, the mobile number for each record will be rendered in the format ********78.

the response now will be

{
    “id”: 143,
    “email”:[email protected],
    “mobile_number”: “********67”
}

And thanks for benchwarmer's help.

Upvotes: 0

benchwarmer
benchwarmer

Reputation: 2774

You can write a method in user model

user.rb

def as_json(options = {})
  # use options as per need
  {id: self.id, name: self.name, mobile: mask}
end

def mask
  # masking logic
end

You can write a method which masks the initial characters and do render json: {data: @user.as_json)}

Checkout this link

Upvotes: 2

Related Questions