首页 > 解决方案 > how to show a specific information from a string of User Agents string saved into my database

问题描述

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.

标签: ruby-on-railsrubyruby-on-rails-4

解决方案


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.


推荐阅读