Adding multiple optional query parameters
Ruby on RailsOne thing I wanted to achieve in Scribbles, and the Tinylytics integration is to dynamically create various query parameter options available with Tinylytics with ease.
Right now Scribbles only allows a few options to be set, but I wanted to be able to set other parameters as and when I get around adding them to the page.
When you have Tinylytics enabled on your site, the app will check for this and add the following snippet to the head of your site:
<% if @blog.tinylytics_site_id.present? %> <script src="https://tinylytics.app/embed/<%= @blog.tinylytics_site_id %>.js<%= @blog.tinylytics_options_query_string(current_user) %>" defer></script> <% end %>
@blog is always available to the page as we're loading the specific
blog in question, otherwise you'll get a generic 404 page.
You may notice the following:
<%= @blog.tinylytics_options_query_string(current_user) %>
This little method basically brings back a query string that we can use with all the options available with Tinylytics, for example showing Kudos.
A blog has various options, so I wanted an easy way to just create parameters on the fly, depending on the options, and just join them all together.
In addition to this, I pass in current_user — which basically either
is you, if it's your blog, or is nil if there is no user logged in to
Scribbles. With custom domains it will always be nil.
Here is method on my Blog model that creates the parameters I need:
def tinylytics_options_query_string(current_user = nil)
params = []
if !current_user.nil? && user_id == current_user.id
params << "ignore"
end
params << "kudos=\#{self.tinylytics_kudos_symbol}" if self.tinylytics_show_kudos
params << "hits" if self.tinylytics_show_lifetime_hits
params << "webring" if self.tinylytics_show_webring
params << "countries" if self.tinylytics_show_countries
params << "uptime" if self.tinylytics_show_uptime
query_string = params.empty? ? "" : "?\#{params.join('&')}"
end
You can see that it dynamically creates the available parameters depending on the blog settings you have set.
This is where I really love Ruby because it's super easy to follow and
love the if in here.
Just an aside, I don't need to use self here, but I like it for
context.
One additional tidbit on Scribbles is that I set a default kudos symbol, 👋, so I pass that in as a kudos parameter option:
params << "kudos=\#{self.tinylytics_kudos_symbol}" if self.tinylytics_show_kudos
Another little extra I do here, especially if you're accessing a blog
via the Scribbles domain is also ignore your own hits using the special
ignore parameter that I added
to Tinylytics not too long ago.
if !current_user.nil? && user_id == current_user.id params << "ignore" end
Each blog belongs to a user, so I check if the current_user that I
passed in earlier isn't nil and if it belongs to the current user that
requested the site.
Super simple but really helpful.