I have a task to find out if an object is created within this month or not. I tried a lot to resolve this. I used 1.month, since(-1), etc. But still I am not on a right track to proceed with these solutions.
I don't think there is a built in way to tell the creation time of an object. You would have to explicitly record the creation time.
class TheClassYouWantToMakeObjects
def initialize
#creation_time = Time.now
...
end
def created_within_same_month?
t = Time.now
t.year == #creation_time.year and t.month == #creation_time.month
end
end
Then, whenever you have object instance of TheClassYouWantToMakeObjects, you can check:
object.created_within_same_month?
Edit:
When you do your request, you compare your creation date with 1.month.since(-1) right?
If so, use instead Time.now.beginning_of_month. Time is a ruby class http://www.ruby-doc.org/core-1.9.3/Time.html
Could you write your request please?
Reedit: Great if it worked. My first explanation was not that explicit, thanks #Andrew.
Related
I've written a filter and use its register-function to load an external CSV-file and fill a bunch of hash-tables. The filter-function then accesses the hash-tables and adds fields to the event. While that's working nicely, the downside is that it only loads once and I'd need to restart logstash to trigger the reload after a change in the CSV-file. Maybe I should add that the filter is currently consuming events coming from three different file inputs.
Writing an input doesn't seem to solve it as the input is not tied to the filter in some way. Therefore, my plan is to somehow reload the CSV-file every few hours or at a particular time and somehow block the entire filter during that, i.e. pause incoming events. That sounds like a weird thing to do and I'm not sure whether or not logstash is actually meant to be used like this.
I'm a newbie regarding Ruby and actually I'm quite amazed that the filter is working this nice. As Google let me down on the entire issue I'm hoping that anyone on here has experience with this, can post a link to an example or can point me to another way of solving this.
For educational purposes I looked into the source of logstash and noticed that I could actually understand what's going on and things are much less complicated than I had thought.
There is a function filterworker in pipeline.rb and a class filterworker and I don't know which one is actually used, but my findings seem to be true for both.
Basically all filters seem to run in one thread in case it's not configured otherwise. This means that I can reload the file anywhere in the filter-function and the entire processing for all filters is paused (input and output might still do something, but that's handled by the queue for the events holding maximum 20 entries).
Therefore, this seems to do it for me:
public
def register
#config_files_read_timestamps = {}
read_config_files
end # def register
def filter(event)
# return nothing unless there's an actual filter event
return unless filter?(event)
read_config_files
:
# filter_matched should go in the last line of our successful code
filter_matched(event)
end # def filter
private
def read_config_files
read_marker_file
:
end
def check_for_changed_file?(filename)
mtime = File.mtime(filename)
#config_files_read_timestamps[filename] ||= Time.at(0)
if #config_files_read_timestamps[filename] < mtime
#config_files_read_timestamps[filename] = mtime
return true
end
end
def read_marker_file
if !check_for_changed_file?("markers.txt")
return
end
:
end
Obviously I don't need a separate thread for the parsing. It would become necessary if I plan to start the reload at a specific time. In that case I'd have to join the thread and then continue with event handling.
Let me know if there could be improvements...
Sorry for such a big question. I do not have much experience with Rails threads and mutex.
I have a class as follow which is used by different controllers to get the license for each customers.
Customers and their licenses gets added and removed every hour. An api is available to get all customers and their licenses.
I plan to create a rake task to call update_set_customers_licenses, run hourly via a cronjob.
I have following questions:
1) Even with a mutex, currently there is a potential for problem, there is a chance that my rake task can occur while updating. Any idea on how to solve this?
2) My design below writes the json out to a file, this is done is for safety as the api is not that reliable. As can be seen, it is not reading the file back, so in essence the file write is useless. I tried to implement a file read but together with mutex and rake task, it gets really confusing. Any pointers will help here.
class Customer
##customers_to_licenses_hash = nil
##last_updated_at = nil
##mutex = Mutex.new
CUSTOMERS_LICENSES_FILE = "#{Rails.root}/tmp/customers_licenses"
def self.cached_license_with_customer(customer)
Rails.cache.fetch('customer') {self.license_with_customer(customer)}
end
def self.license_with_customer(customer)
##mutex.synchronize do
license = ##customers_to_licenses_hash[customer]
if license
return license
elsif(##customers_to_licenses_hash.nil? || Time.now.utc - ##last_updated_at > 1.hours)
updated = self.update_set_customers_licenses
return ##customers_to_licenses_hash[customer] if updated
else
return nil
end
end
end
def self.update_set_customers_licenses
updated = nil
file_write = File.open(CUSTOMERS_LICENSES_FILE, 'w')
results = self.get_active_customers_licenses
if results
##customers_to_licenses_hash = results
file_write.print(results.to_json)
##last_updated_at = Time.now.utc
updated = true
end
file_write.close
updated
end
def self.get_active_customers_licenses
#http get thru api
#return hash of records
end
end
I'm pretty it's the case that every time rails loads, the environment is "fresh" and has no concept of "state" in between instances. That is to say, a mutex in one ruby instance (the one request to rails) has no effect on a second ruby instance (another request to rails or in this case, a rake task).
If you follow the data upstream, you'll find that the common root of every instance that can be used to synchronize them is the database. You could use transactional blocks or maybe a manual flag you set and unset in the database.
I'd like to access Delayed::Worker instance to call say on it to save some messages in delayed_log file. Is there any simple way to achieve such behaviour?
class SomeDelayedJob
def perform
worker = __?__ # Delayed::Worker instance which called that perform method
worker.say('going to do x')
do_x()
end
end
Your best bet would be to use
Delayed::Worker.logger.[info|error|warn|debug] "going to do x"
with some formatting :)
because say internally uses the same logger object
Edit
Delayed::Worker.logger.[info|error|warn|debug] "#{Process.pid} at #{Time.now} => going to do x"
Hope this help
i am new to ruby and nanoc. I am trying to sort articles based on time. So I get more accurate results on my blog.
This is what I am using in my sorted_articles_time.rb file under /helpers/
def sorted_articles_time
articles.sort_by do |a|
attribute_to_time(a[:time])
end.reverse
end
But then I get the error
NoMethodError: private method `sorted_articles_time' called for #<Nanoc::Site:0x007fd93b0a3f40>
What am I doing wrong ? And is there a way to overwrite the existing sorted_articles method ?
Thanks
UPDATE: I already have it initiated in the rake file. So I think my rake file is fine here.
time1 = Time.new
#time = time1.inspect
Are you calling #site.sorted_article_times? If so, leave off the #site part. Helpers are intended to be called as functions, not as methods on #site.
Use a scrope from your model. Check this activeactive_record_querying this is the best place to sort your articles.
Each time I add in the correct code, it gives me the same error due to AboutMethods:0x00000101841a28 number changing each time. It's like its stuck and I don't know how to get out this loop. It worked once, then I went on to the next step, but then it triggered an error after that.
I must not be inputting the correct line of code given from the console?
def test_calling_private_methods_with_an_explicit_receiver
exception = assert_raise(NoMethodError) do
self.my_private_method
end
assert_match "private method `my_private_method' called for #<AboutMethods:0x000001008debf8>", exception.message
end
The AboutMethods:0x000001008debf8 changes each time, not sure how to approach this problem?
AboutMethods:0x... is the output of the inspect method, which usually (and in this case) includes the class name (AboutMethods) and the object id (0x...). The object id is related to the objects location in memory, so it will change every time.
In my experience, there is very little value to checking the string from an exception (it's brittle). However, if you feel the need, use a regex:
assert_match /private method `my_private_method' called for \#\<AboutMethods:.*/