0

I am working with Geolocation and I have a string of User Agent saved into my database as shown below:

Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36

In this case of the string above, the information I would like to output in my views is Macintosh; Intel Mac OS X 10_13_6. So, in the frontend/views, I don't want to output the whole data as its in the database. All I want to pick from this information is just to show the devise the user used to login into the application, and I do not know how I will show only what I want. Any help or pointer to what I should do will be appreciated.

view

.row
  .panel.panel-primary
    .panel-heading
      span = t('admin_header.traffics')
    .panel-body
      = table_for(@traffic, class: 'table table-condensed table-hover') do |t|
        - t.column :ua, 'Device Used', class: 'col-xs-1' # But this shows all the string which I do not want, I only want specific details from it.

Here is the code that saves User Agent string into the Database:

  def save_signup_history(member_id)
    SignupHistory.create(
      member_id: member_id,
      email: @member.email,
      ip: request.remote_ip,
      accept_language: request.headers["Accept-Language"],
      ua: request.headers["User-Agent"], #Here is User Agent
      login_location: get_ip_location
    )
  end

The only thing I can think of is to use .remove method, but I don't think its a best solution to my problem.

2 Answers 2

1

How about using the user_agent gem?

In the specific example you gave you could use:

user_agent = request.env['HTTP_USER_AGENT']
user_agent.match(/\(.*?\)/)[0]

However that may not cover every case, and either using a gem or code which accounts for the various options is your best bet.

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

1 Comment

This looks nice to me. However, if I need to show only the platform without the parenthesis, such as Macintosh alone, how do I deal with that?
0

You can use the scan method to get the string you need. Example:

user_agent = Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36

then,

user_agent.scan(/Mac.*_6/)

should give you your desired string. You can modify it as per your requirements.

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.