1

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.

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

5 Comments

i have executed what u have said but in a different way render json: {data: @user.as_json(only: [:id, :email]), methods: :mask}, but i having response { "id": 121, "email":"[email protected]", "mask": "********45"} ie the name of the method is the key of the mobile number. Can please find out what is the problem.
You can name the method whatever you want in json response
Thats where the problem is i need the response to be mobile number but for the masking logic "********" + self.mobile_number.slice(8,9), if the method name is mobile_number it will cause a infinite loop.
yes it is working right now. Thanks for your help.., but i have another issue, i have some columns to be excluded and some to be included it differs on different action, but if if am overriding the as_json like this i will not able to do so., is there any other alternatives.
Now i have solved it by using render json: {data: @user.as_json(only: [:id, :email]).merge(mobile_number: @user.mask)} but there is a another problem there are certain actions in which i need to show a list of user, this solution won't suit there.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.