user6589814 user6589814 - 2 months ago 6
Ruby Question

Ruby on Rails - Showing different code (button) every 2 user

I'm running

Rails 4.2.2
in my application. There is some part of my website that I would like to display different code/element every 2 user.

I know I can achieve this with
split gem
but its not a A/B testing and I don't want to make it complicated.

So basically it works like this:

Visit 1:
<button>Login</button>


Visit 2
<h1>Welcome to our website</h1>


Visit 3:
<button>Login</button>


Visit 4
<h1>Welcome to our website</h1>


etc

Is it any way I can achieve this without 'split gem' or some sort of
A/B testing gem
.

Answer

You can achieve this with simple rand method

<% if rand(2).zero? %>
  <button>Login</button>
<% else %>
  <h1>Welcome to our website</h1> 
<% end %>

EDIT

If you have more than 2 elements then its better to go for hash or case statement

Create a helper method

def conditional_element(option)
  hash = {
    0 => "<button>Login</button>",
    1 => "<h1>Welcome to our website</h1>",
    2 => "Some other element"
  }
  hash[option]
end

OR

def conditional_element(option)
  case option
  when 0
    "<button>Login</button>"
  when 1
    "<h1>Welcome to our website</h1>"
  when 2
    "Some other element"
  end
end

And use it in view

<%= conditional_element(rand(3)) %>

NOTE: You need to change the number in rand as per your number of elements

Comments