Code Monkey home page Code Monkey logo

rails-timeago's Introduction

rails-timeago

Gem Version Build Status

rails-timeago provides a timeago_tag helper to create time tags usable for jQuery Timeago plugin.

Installation

Add this line to your Gemfile:

gem 'rails-timeago', '~> 2.0'

And then execute:

$ bundle

Or install it yourself as:

$ gem install rails-timeago

Use bundled JavaScript with Sprockets

Note: The bundled JavaScript can only be used with sprockets. Rails-webpacker cannot load scripts bundled with the gem. If you use rails-webpacker you need to install, load, and setup jquery-timeago on your own.

To use bundled jQuery Timeago plugin add this require statement to your application.js file:

//= require rails-timeago

This will also convert all matching time tags on page load.

Use the following to also include all available locale files:

//= require rails-timeago-all

If using a recent Rails with rails-ujs, jQuery might not be present anymore. You need to add jquery-rails to your Gemfile and load it, e.g.:

//= require jquery
//= require rails-timeago
//= require rails-timeago-all

Usage

Use the timeago_tag helper like any other regular tag helper:

<%= timeago_tag Time.zone.now limit: 10.days.ago %>

Available options:

date_only Only print date as tag content instead of full time. (default: true)

format A time format for localize method used to format static time. (default: default)

limit Set a limit for time ago tags. All dates before given limit will not be converted. (default: 4.days.ago)

force Force time ago tag ignoring limit option. (default: false)

default String that will be returned if time is nil. (default: '-')

title A string or block that will be used to create a title attribute for timeago tags. It set to nil or false no title attribute will be set. (default: proc { |time, options| I18n.l time, format: options[:format] })

All other options will be given as options to the time tag helper. The above options can be assigned globally as defaults using

Rails::Timeago.default_options limit: proc { 20.days.ago }

A global limit should always be given as a block that will be evaluated each time the rails timeago_tag helper is called. That avoids the limit becoming smaller the longer the application runs.

I18n

rails-timeago 2 ships with a modified version of jQuery timeago that allows to include all locale files at once and set the locale via an option or per element via the lang attribute:

<%= timeago_tag Time.zone.now, lang: :de %>

The following snippet will print a script tag that set the jQuery timeago locale according to your I18n.locale:

<%= timeago_script_tag %>

Arguments are passed to Rails' javascript_tag helper, e.g. to assign a CSP nonce: timeago_script_tag(nonce: true).

Just insert it in your application layout's html head. If you use another I18n framework for JavaScript you can also directly set jQuery.timeago.settings.lang. For example:

jQuery.timeago.settings.lang = $('html').attr('lang')

Do not forget to require the needed locale files by either require rails-timeago-all in your application.js file or require specific locale files:

//= require locales/jquery.timeago.de.js
//= require locales/jquery.timeago.ru.js

Note: English is included in jQuery timeago library, but can be easily override by include an own file that defines jQuery.timeago.settings.strings["en"]. See a locale file for more details.

rails-timeago includes locale files for the following locales taken from jQuery Timeago.

Your customized jQuery locale files must be changed to work with rails-timeago 2. Instead of defining your locale strings as jQuery.timeago.settings.strings you need to define them like this:

jQuery.timeago.settings.strings["en"] = {
    ...
}

License

MIT License

Copyright (c) 2014, Jan Graichen

rails-timeago's People

Contributors

beenashetty avatar chloerei avatar cyu avatar dependabot-support avatar dmitriy-kiriyenko avatar domoritz avatar drcapulet avatar iwiznia avatar jgraichen avatar juno avatar mprokopov avatar msokk avatar renovate-bot avatar renovate[bot] avatar ressu avatar rmm5t avatar sunny avatar yiichou avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rails-timeago's Issues

It seems like timeago_tag is very slow.

When I call timeago_tag in a view 30 times and measure the response time by rack-mini-profiler, the response time is over 1600ms, but without calling timeago_tag 30 times, it was just 511ms.

rails (4.0.0)
rails-timeago (2.7.1)

no way to set option allowFuture

from documentation:

To support timestamps in the future, use the allowFuture setting:
jQuery.timeago.settings.allowFuture = true;

but here is no such option support in gem

Support for CSP nonce

When using timeago_script_tag in an application that has a Content Security Policy enabled, this script is blocked.

In most other places, this is usually solved by allowing nonce: true as an argument. The query-diet gem might be a good example.

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Awaiting Schedule

These updates are awaiting their schedule. Click on a checkbox to get an update now.

  • chore(deps): lock file maintenance

Detected dependencies

bundler
Gemfile
github-actions
.github/workflows/test.yml
  • ruby/setup-ruby v1
  • ruby/setup-ruby v1
  • ubuntu 22.04
  • ubuntu 22.04
regex
rails-timeago.gemspec
  • actionpack >= 5.2
  • activesupport >= 5.2
Gemfile
  • jgraichen/rubocop-config v12
.github/workflows/test.yml
  • ruby 3.3.4

  • Check this box to trigger a request for Renovate to run again on this repository

Rspec failing because it cannot find required resource in application.js

I'm developing a Rails 4.1 app, and this gem works really great.

But just after including it, I run my feature specs (rspec + capybara) and all feature specs fail. The error is the following:

 ActionView::Template::Error:
   couldn't find file 'rails-timeago'
     (in /Users/ernesto/code/projects/dd/app/assets/javascripts/application.js:16)
 # ./app/views/layouts/application.html.haml:9:in `_app_views_layouts_application_html_haml___1471316763353983852_70239779384000'
 # ./spec/features/sign_in_process_spec.rb:69:in `block (3 levels) in <top (required)>'
 # ./spec/features/sign_in_process_spec.rb:67:in `each'
 # ./spec/features/sign_in_process_spec.rb:67:in `block (2 levels) in <top (required)>'

The error occurs in the line of the app/assets/javascript/application.js file where rails-timeago is required:

//= require rails-timeago

However, in development, everything works. I even added recently another assets-related gem (chosen-rails), with the corresponding "require" line in application.js and my feature specs work. But as soon as I require rails-timeago, they all fail.

Any ideas?

License missing from gemspec

Some companies will only use gems with a certain license.
The canonical and easy way to check is via the gemspec,

via e.g.

spec.license = 'MIT'
# or
spec.licenses = ['MIT', 'GPL-2']

Even for projects that already specify a license, including a license in your gemspec is a good practice, since it is easily
discoverable there without having to check the readme or for a license file. For example, it is the field that rubygems.org uses to display a gem's license.

For example, there is a License Finder gem to help companies ensure all gems they use
meet their licensing needs. This tool depends on license information being available in the gemspec. This is an important enough
issue that even Bundler now generates gems with a default 'MIT' license.

If you need help choosing a license (sorry, I haven't checked your readme or looked for a license file), github has created a license picker tool.

In case you're wondering how I found you and why I made this issue, it's because I'm collecting stats on gems (I was originally looking for download data) and decided to collect license metadata,too, and make issues for gemspecs not specifying a license as a public service :).

I hope you'll consider specifying a license in your gemspec. If not, please just close the issue and let me know. In either case, I'll follow up. Thanks!

p.s. I've written a blog post about this project

change default options one time?

How can I change limit option (default 4.days.ago) to another value for all times when I will use "timeago_tag", or lang option too.

Because repeat option each time it's boring and not good way to maintain.

Incorrect time ago text

If the current time is: 2016-06-27 15:33:00 UTC

And the article was posted at 2016-06-27 15:02:26 UTC

I am getting: <time datetime="2016-06-27T15:02:26Z" title="Mon, 27 Jun 2016 15:02:26 +0000" data-time-ago="2016-06-27T15:02:26Z">about 17 hours</time>

As you can see the datetime and title is correct but the inner text is saying 17 hours... Why is this? The current time is being rendered on the same view using Time.zone.now so that's correct, but for some reason the gem thinks it's 17 hours different :/

Here is the code:

<%= timeago_tag article.created_at, :nojs => true, :limit => 10.days.ago %>

I'm using this inside an each loop and I've also noticed that ALL of the articles are saying 17 hours...

Here is the full code:

<% @articles.each do |article| %>
      <tr>
        <td><%= link_to article.title, article_path(article) %></td>
        <td><%= timeago_tag article.created_at, :nojs => true, :limit => 10.days.ago %><br><%= article.created_at %></td>
        <td><%= link_to 'Edit', edit_article_path(article) %></td>
        <td><%= link_to 'Destroy', article_path(article),
                        method: :delete,
                        data: { confirm: 'Are you sure?' } %></td>
      </tr>
  <% end %>

In fact EVEN if I use:

<%= timeago_tag Time.zone.now, :nojs => true, :limit => 10.days.ago %>

outside of the each loop, I am still seeing 17 hours! So it seems that the helper is confused how to work out the time ago (without the JS). And the loop isn't the reason because this with just the Time.zone.now and outside of it.

Please add changelog

It would be easier to read then reading every commit
Also reminds the author(s) to recheck all changes and make doc update before releases
(like I don't see any doc about #25)

Timeago helper not working without setting up helper or initializer

When this gem is first install on a Rails 5.1.6, it wasn't clear that I had to add to timeago helper:

Rails::Timeago.default_options :limit => proc { 20.days.ago }, :nojs => true

It was difficult to figure this out right away. It'll be nice to have a generator to make it easier for users to install and plug in the helper.

Option to remove title or no title by default?

We're using bootstrap and our titles get translated into tooltips. It seems like there's no way to avoid having the title set using the helper and this isn't a required feature for the time tag or for timeago so I'm not sure why it's enforced.

inconsistent rendering

<%= timeago_tag Time.zone.now %>
<%= timeago_tag message.created_at %>

render, respectively,

2013-01-08
2013-01-04

and the second one is not caught by the jquery and the content remains static at 2013-01-04

Not working on ajax success

Hey,

It seems that ajaxically loaded content is not handled properly despite the on('ajax:success') here.

I am guessing ajax:success is related to turbolinks, but since I disabled it, timeago is not applied to new content.

The solution is simple - I believe you should add ajaxSuccess to the on() event.

This is my coffeescript snippet I use to ajax-load the new content:

    $.ajax(url: url).done (html) ->
      $('#live').html(html)

And this is my workaround to make timeago work for now:

  $(document).on 'ajaxSuccess', ->
    $('time[data-time-ago]').timeago();

I18n

Hello
I added jquery.timeago.ru.js to config/locales directory, but I don't have localized datetime ago. Can you help me?

I18n doesn’t work at all on heroku

When trying to use my app on heroku, I get this error:
Sprockets::Helpers::RailsHelper::AssetPaths::AssetNotPrecompiledError in [PROJECT_ROOT]/vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.3/lib/sprockets/helpers/rails_helper.rb:142

I tried to specify locales to include in Rails::Timeago.locales but it does not work any better.

Timeago fails to work in incognito Chrome mode

I am getting kind of weird bug with TimeAgo Rails.

So, given <%= timeago_tag Time.now, nojs: true, class: 'timeago-time', limit: nil %> every other browser works fine, producing 6 minutes ago and so on. BUT Chrome + incognito more on iPhone is behaving in a strange way: I am getting 1) about 14 hours 2) without a word ago

Please help me to deal with it. What is the possible fix here?

jquery.timeago.en.js not being read for :en locale

Could I please confirm where the English locale file (presumably jquery.timeago.en.js) is meant to be in the file structure of a Rails app? If I have multiple locales, and am hence using the timeago_script_tag in my html head tag, and I have the relevant locale files (jquery.timeago.xx.js) in the assets/javascripts/locales/ directory, my jquery.timeago.en.js file is never read in for the :en locale. Instead, the last locale file alphabetically in the locales directory ends up being used. If I don't use the timeago_script_tag in my app's head tag, then I get the correct English strings, I'm assuming from the gem's vendor/assets/javascripts/jquery.timeago.js file. It seems the issue is with the last two lines of code in the lib/rails-timeago/helper.rb file:

def timeago_script_tag(locale = nil)
  locale = ::Rails::Timeago.lookup_locale locale
  return javascript_include_tag 'locales/' + ::Rails::Timeago.locale_file_name(locale) if locale != "en"
  ''
end

Once I changed the code in my fork to:

def timeago_script_tag(locale = nil)
  locale = ::Rails::Timeago.lookup_locale locale
  javascript_include_tag 'locales/' + ::Rails::Timeago.locale_file_name(locale)
end

assets/javascripts/locales/jquery.timeago.en.js as well as my other locale fies were read in as expected. I was going to submit a pull request but looking at the tests in spec/timeago/helper_spec.rb, it seems that not having a jquery.timeago.en.js is by design:

context "#timeago_script_tag" do
  it "should not return anything if locale is 'en'" do
    I18n.locale = "en"
    @stub.timeago_script_tag.should == ""
  end
  # ...

So, where should the English locale file be in my Rails app if I have multiple locales, and what should it be called?

I18n in production

I have some troubles with this gem in production mode.
I have three locales - en, ru, uz
All locale files are requiered in application.js.coffee.
I have this error:

   "NetworkError: 404 Not Found - http://playground.todo.uz/falselangs/ru.js"

And always only one language is selected, even when locale changes

timeago does not run in production

I have included this gem into my project and it works great until it hits production.

application.js:

//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require bootstrap
//= require rails-timeago
//= require_tree .

I change a setting to allow future dates using:
$.timeago.settings.allowFuture = true;

This works in dev but when it hits heroku in either stage or production timeago cannot be found.

I can see that the plugin is included in my compiled js file but it does not seem to be attached to the $ object

Add package.json

New Rails projects can use Webpacker so is it would be good to support them by adding a package.json

jQuery no conflict

Hello,
We are using both Prototype and JQuery in our current project. To avoid any sort of conflict, you could replace $ with jQuery in rails-timeago.js (line 7).
Cheers,
Nicolas

Incorrect "time ago in words" when rendering partials of newly created items without page refresh

Hi thanks for this gem. I'm having an issue displaying the correct "time ago in words" when rendering a partial via ajax.

For example, after I create a new post and it's inserted into the page's DOM without refreshing, the time tag shows "about 14 hours". But when I refresh the page the time tag shows "less than a minute ago".

Here's the code I'm using to render the time tag:

<%= timeago_tag post.created_at, :nojs => true, :limit => 10.days.ago %>

Should enable future date by default

This gem is doing a great job at simplifying live timestamp in rails.

I believe it should enable support for future dates by default, or at least provide an easy way (initializer option) to do so.

Even after following the discussion in issue #7 , I was unable to make it work without the need to add extra options to future dates.

I have added this to my application head:

<script>jQuery.timeago.settings.allowFuture = true;</script>

I have tested that future date works with this:

<%= timeago_tag 1.hours.from_now, force: true %>

But, what I really want is for this to work:

<%= timeago_tag Time.now %>
<%= timeago_tag 1.hours.from_now %>

Adding the limit option to an initializer, breaks one of the above (depends on whether the limit is in the past or future), and using the force option has the undesired side effect of ignoring the limit.

If there is a way around it, I think it should be mentioned somewhere clearly in the README, even if the suggestion to make it work out of the box is rejected.

EDIT

Also, I am not sure if its a bug or a feature - but most likely related.
I was expecting the below two blocks to work the same. Pasted here as a repro case:

<h2>Doesnt work (first line is not converted)</h2>
<br><%= timeago_tag Time.now,         limit: 3.days.from_now %>
<br><%= timeago_tag 1.hours.from_now, limit: 3.days.from_now %>

<h2>Works</h2>
<br><%= timeago_tag Time.now,         force: true %>
<br><%= timeago_tag 1.hours.from_now, force: true %>

Getting wrong time in when used with action cable

I am getting two hours ago for new messaged when used with Action cable.

<div class="message">    
<div class="media">
  <div>
    <%= link_to image_tag(message.user.avatar.url(:mini), :class => "pull-left media-left img-circle"), message.user %>
  </div>
  <div class="media-body">
      <%= link_to message.user.name, message.user, :class => "footerlinkhover" if message.user %>
      <%= message.body %>
      <span class="chattime">
          <%#= time_ago_in_words(message.created_at).gsub('about','') %>
          <i><%= timeago_tag (message.created_at), :nojs => true, :limit => 10.days.ago %></i>
      </span>
  </div>
</div>
</div>

image

This is after refreshing the page.

image

limit isn't preventing conversion

I have a limit set, but it seems to still convert.

Tried both

timeago_tag(tmstmp, :nojs => true, :limit => proc { 1.days.ago })

and

timeago_tag(tmstmp, :nojs => true, :limit => 1.days.ago)

Also tried days as singular.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.