迂回的实现了覆盖 helper 中的函数
终于搞定了 Chito 的相对时间插件,早就想实现这个插件了,不过一直没有想出好的实现方法,目前这方法虽然有点迂回,不过总体效果还是不错,也给以后的插件开发带来了很大的方便~
比如早先是用 post_time 这个 helper 来显示文章的发表日期的:
-
def post_time
-
@post.created_at.strftime("%Y年%m月%d日 %I:%M%p")
-
end
这样就显示的是诸如 '2008年1月1日 10:30AM' 这样的时间。
如果想改成显示相对时间,首先想到的就是覆盖这个方法,重定义 post_time 这个函数。不过目前 Chito 的插件方式和 Rails 的插件方式是一样的,都是在 vendor/plugins 目录下,也就是说,插件的函数要在主程序之前就被加载,这种方法行不通。
而且,即使可以成功覆盖,最初的 post_time 也就无法引用了,如果想在运行中切换显示正常时间和相对时间,就很麻烦了,除非覆盖前用 alias_method 把最初的 post_time 换个名字,否则没法引用到原来的函数。
最后决定使用这个方法,先定义一个 rewriter 函数:
-
def rewriter
-
caller_method = (caller[0] =~ /`([^']*)'/ and $1)
-
rewriter_method = "rewriter_of_#{caller_method}"
-
if @user.send("enable_#{rewriter_method}") && respond_to?(rewriter_method)
-
send(rewriter_method)
-
else
-
yield
-
end
-
end
然后把最初的 post_time 改成:
-
def post_time
-
rewriter{ @post.created_at.strftime("%Y年%m月%d日 %I:%M%p") }
-
end
这样,如果在插件中定义了 rewriter_of_post_time 这个函数,并且用户激活的显示相对时间的选项 ( @user.enable_rewriter_of_post_time 为 true ),就会显示相对时间,否则就显示最初的正常时间:
-
def rewriter_of_post_time
-
time_ago_in_words(@post.created_at) << '前'
-
end
有了 rewriter 覆盖其他的函数也方便了,只需加个 rewriter { ... } 就 OK 了,相当一个 hook 的作用,而且 rewriter_of_post_time 这个函数,从名字一眼就能看出是干啥的了~
把相对时间插件插件文件夹删掉,对 Blog 也没有影响,运行中只要改变 @user.enable_rewriter_of_post_time,就可以切换显示。
按照这种方式,下次尝试实现一下 header{ ... } 或者 footer { ... },在 helper 的内容前面和后面追加内容~
2019年5月11日 10:03
download sad whatsapp status through this site.
2021年3月06日 20:44
This is a great inspiring article.I am pretty much pleased with your good work.You put really very helpful information. Keep it up. Keep blogging. Looking to reading your next post. 토토
2021年3月08日 19:42
pleasant post, stay aware of this fascinating work. It truly regards realize that this subject is being secured likewise on this site so cheers for setting aside time to talk about this! 토토사이트
2021年3月09日 04:10
Recruitly® is built to streamline Recruiting agency software processes and help businesses grow as a result. Recruiting agency software
2021年3月13日 16:03
Thank you for taking the time to publish this information very useful! 먹튀검증사이트
2021年3月13日 16:21
Most of the time I don’t make comments on websites, but I'd like to say that this article really forced me to do so. Really nice post! Gentleman tracksuit
2021年3月14日 16:06
If someone week i really ashen-haired not actually pretty, whether you will lite grope a present, thought to follow us to displays bursting with ends of the earth considerably? Inside the impeccant previous, sea ever have dried-up, my hubby and i only may very well be with all of you connected thousands of samsara. www.signinsupport.net
2021年3月16日 00:13
Thanks for sharing nice information with us. i like your post and all you share with us is uptodate and quite informative, i would like to bookmark the page so i can come here again to read you, as you have done a wonderful job. srh vs mi
2021年3月17日 15:55
Nice post! This is a very nice blog that I will definitively come back to more times this year! Thanks for informative post. safestore auto
2021年3月17日 17:22
I know the value of the https://essaywriter.org/college-paper-for-sale for my personal assignment. The scope of the writer is fit for the attachment for all issues. The skills are piled for the realm for the mid of the terms for all goals for the universities.
2021年3月20日 18:08
Simple Moving Company established to provide stress free moving services. We are fully licensed and insured full service local and long distance moving company. Our goal is to provide excellent customer service, fast deliveries and successful relocation to all our customers. We know moving isn’t easy and a very stressful event and we make sure that you will have a SIMPLE move. To arrange movers, please contact us at your convenience. We look forward to meeting you soon. HEADQUARTER ADDRESS 1919 VINEBURN AVE, STE 04, LOS ANGELES, 90079 best moving company
2021年3月21日 17:57
I know your expertise on this. I must say we should have an online discussion on this. Writing only comments will close the discussion straight away! And will restrict the benefits from this information.
2021年3月21日 18:07
Affordable Pool Remodeling New Hampshire, Boston, All MA | Pool Plastering and Resurfacing Pool Coping Repair
2021年3月22日 20:13
click here website read more click here website read more click here website read more click here website read more click here website read more click here website read more click here website read more click here website read more click here website read more click here website read more click here website read more click here website read more click here website read more click here website read more click here website read more click here website read more click here website read more click here website read more
2021年3月23日 16:35
This is my first visit to your web journal! We are a group of volunteers and new activities in the same specialty. Website gave us helpful data to work. فيب
2021年3月24日 17:45
I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post. walmart wire login
2021年3月25日 16:37
Yes i am totally agreed with this article and i just want say that this article is very nice and very informative article.I will make sure to be reading your blog more. You made a good point but I can't help but wonder, what about the other side? !!!!!!Thanks Profile Backlinks Services
2021年3月25日 17:13
I needed to thank you for this incredible read!! I unquestionably adored each and every piece of it. I have you bookmarked your site to look at the new stuff you post. google ranking check
2021年3月25日 18:22
Cash App is a mobile payment service, allowing users to transfer money to one another using a mobile app. Even after having tough competitors like PayPal, Venmo, Zillay Pay in the market, CashApp still efficiently managed to make its significant place with an incredible performance. with millions of active users. Cash App Business
2021年3月25日 19:44
Particular interviews furnish firsthand message on mart size, industry trends, ontogeny trends, capitalist landscape and outlook, etc. https://amirabelladesigns.com/
2021年3月25日 20:15
Pool Perfection, Every Time Contact us today for a free estimate for your pool repair, remodeling, or new construction needs both residential and commercial. pool coping repairs
2021年3月25日 21:19
I genuinely believed you would probably have something useful to say. All I hear is a bunch of whining about something that you can fix if you were not too busy looking for attention. After all, I know it was my choice to read.. https://amirabelladesigns.com/
2021年3月27日 02:10
Faux leather or can be named Synthetic leather or Imitation leather or Artificial leather, There are 3 primary types of faux leather fabrics Faux Leather ViewPoint, Please visit our website to get the best & honest information for all kind of leathers.
2021年3月27日 14:48
I truly value this superb post that you have accommodated us. I guarantee this would be helpful for a large portion of the general population. Onewheel Accessory
2021年3月27日 17:50
Wow, this is really interesting reading. I am glad I found this and got to read it. Great job on this content. I like it. rigid flex PCB
2021年4月01日 18:17
Nice post! This is a very nice blog that I will definitively come back to more times this year! Thanks for informative post. Winter Tires Ottawa
2021年4月03日 23:55
Xander Technology Solutions | Video Marketing Service | Digital Marketing Agency ppc agency
2021年4月04日 14:07
I know your aptitude on this. I should say we ought to have an online discourse on this. Composing just remarks will close the talk straight away! What's more, will confine the advantages from this data. Onewheel Accessories
2021年4月06日 20:38
I needed to thank you for this incredible read!! I unquestionably adored each and every piece of it. I have you bookmarked your site to look at the new stuff you post. Managed IT Support companies Westwood Los Angeles, California
2021年4月08日 17:47
Cool stuff you have got and you keep update all of us.
2021年4月09日 02:44
Sky Marketing strives to be Pakistan's biggest real estate developer ever, guaranteeing the highest international standards, prompt execution, and lifetime customer loyalty. With projects like park view city review.
2021年4月11日 04:07
Buy Pharmacy grade drugs to boost stamina and enhance performance. Buy HGH, mens sexual health products, weight loss remedy, EPO and Clenbuterol Buy Online. Buy Clenbuterol 40mcg
2021年4月13日 01:30
Affordable Pools Inc. Pool Remodeling | Pebble Plaster. Tile and Coping, Decking; Indoor Pools, Spa and New Pool Construction! Boston Gunite Pool Renovations | Whether your residential pool needs a refresh, or you’re a commercial pool owner in need of a complete redesign, Affordable Pools is your only source for pool repair and remodeling in Boston, Massachusetts, Rhode Island, Vermont, Maine, Connecticut, ;and all across New England. Affordable Pools is ready to help you make your pool look brand new. Contact us today for a free estimate for your pool repair, remodeling, or new construction needs both residential and commercial. pool repair Massachusetts
2021年4月13日 15:07
We provide you with Monin products from Syrup, coffee sauce and many other products through the Arzaq app.Free delivery of your first order, download it to your mobile phone, by scanning the QR code in the image with your mobile phone's camera. نكهات القهوة
2021年4月15日 01:02
Over 2134+ students already improved their performance using the Class Companion Try us for free today, and understand why complex attendance is a thing of the past. Classroom Management Software
2021年4月15日 16:33
2021年4月16日 14:06
Simple Empathy is a collaborative wellness space that provides mental health psychotherapy, acupuncture, Chinese Medicine, massage & reiki. We work together with all modalities to help heal what ails you from the inside out. natural healing center
2021年4月24日 20:56
HOVERBOARD UK: Buy British Hoverboards for Sale UK HOVERBOARD UK
2021年4月26日 20:32
Lavington Designs - Visit our website for Premium & High Quality Personalized Gifts for Adults and Children, Quality Personalized Clothing, Totes, Travel Bags and Kids Gifts - Get the latest updates on new products and upcoming sales. Personalized Gifts
2021年4月28日 00:35
Watch this informative video on youtube about How to Leave a Medicare Advantage Plan | UPDATED for 2021 ; or How to get off of a Medicare Advantage Plan. Thank You. How to Leave a Medicare Advantage Plan
2021年5月12日 17:00
This is a great high resolution screen which you have shared for the users. Making a website is not an easy task but managing a good website is really a hard work. As far as this website is concerned, I am very happy. eye doctor Tulsa
2021年5月14日 13:44
Lets talk about why you should schedule regular checkups with your doctor and how beneficial it is to your life. Regular Checkup Benefits
2021年5月16日 05:04
#1 Scrap Car Removal Service – Contact us now or get a quote & get an instant offer & the highest value cash on the spot we are the #1 leading scrap car removal mississauga company in the GTA west areas pay big dollar/cash for cars on the spot, and offers free towing service.
2021年5月16日 17:19
Great article with excellent idea!Thank you for such a valuable article. I really appreciate for this great information.. saunas
2021年5月30日 18:18
Custom Printed Posters A4 A3 A2 A1 A0 | Digital Printing Online, Our Custom printed posters are larger than life! Choose A1 Poster Printing, A2 Poster Printing, A0 Poster Printing size printed posters to advertise an event, promote business, or display a safety notice. Need help? Call our friendly support team at (01908) 696999 Or, Please visit our website for more details.
2021年6月05日 12:24
If you live in the Mississauga Ontario areas and are looking for scrap car removal in Mississauga, Top Cash scrap cars removal offers the best & instant prices for your old Clunkers car scrap yard mississauga
2021年6月14日 03:17
Best New Bingo Sites 2021 A2Z Sister Site | The Best Place To Find Casinos & their Sister Sites, UK Largest Casino SisterSites ListChoose from A-Z catalogue with best offers. Please visit our website for more information and limited offers. Thank You.
2021年6月15日 04:44
Hi, We provide a stone library and granular project management digital dry layout DDL is an all in one toolbox for stone blendings, offers and estimates. Please visit our website for more details. Thank You.
2021年6月15日 13:34
If you are looking for Orignal Seiko Men's and Women's watches Please click here to visit Benelli Jeweler Website. A center for watches, jewelry, repairs and gold purchasing. You will also find best quality of smartwatches.
2021年6月16日 00:41
Nouveau is committed to bringing high Quality tailor-made genuine & premium faux & genuine leather backpacks for women, leather handbags & purses for women, leather shoulder bags & purses for women all over the world you can Buy Women backpacks from our Website . Every bag is shipped direct in a dust bag for protective storage. And we are currently including a Free branded Nouveau drawstring shopping backpack with every purchase. Grab one for yourself and as incredible gifts for the fashionistas in your life.
2021年6月16日 01:10
The variety of the online casino in India is approaching the level in Las Vegas, and one can truly have benefits out of this fact! So, now you can play casino online in some of the Indian states—or even the whole country! And you know what it means: online casino play for real money is a perfect way to get rich! Please visit this website to get know more about it. Thank You visit
2021年6月22日 20:33
Please vist this Website to get information about natural healthy recipes, health, wellness, environment, circular economy. I tried to create something different than putting hundreds of recipes into a pot. Each recipe has a few things going for it, I try to give scientific, nutritional and more information. Because I believe that sustainability and circular economy starts and ends from what we eat, and what we eat is infinitely important for our health.
2021年6月24日 17:16
Get 10% Off on Your first Order. Explore our range of Traditional Rugs, from traditional Persian detailing to traditional Middle Eastern gems We have a traditional rug and floor covering for every type of home Why settle for anything less Explore our affordable traditional rugs online. Please visit out website for more exploring our highert quality cheap buy traditional rugs in UK.
2021年6月28日 20:20
This is such a great resource that you are providing and you give it away for free. I love seeing blog that understand the value of providing a quality resource for free. บาคาร่า
2021年7月01日 17:53
Online Bingo is the most popular online game, Our best bingo sites list could save lots of searching time for you to find your favorite bingo sites and their sister sites confidently to play with the latest bonus and welcome offers.
2021年7月05日 20:04
Sign up and get 10% Off, BuffK 9® Dog Supplements specialize in natural vitamins and supplements for ALL dogs! Improved lean muscle, endurance, joint health and overall well being! Visit this website for natural & Best Dog Supplements & Vitamins. At BuffK-9® Dog Supplements we specialize in healthy, 100% safe, 100% natural, side-effect free supplements for ALL family dogs. Best Dog Supplements & Vitamins
2021年7月08日 20:29
The farmmaster tractors are full of the latest and most advanced technological features that make farming extremely easy and efficient. Compact tractors with the right attachment can take on any task, big or small Beckside Machinery has a compact tractor attachment or accessory to help you with, - Maintaining grounds, whether large or small, as well as carrying out jobs around the farm, are both necessary musts. FarmMaster
2021年7月13日 03:28
dove for sale | Buy Quality Bird Cages & The Best Dove Breeds, Shop Doves World™ for low prices on the best dove breeds and bird cages. Doves World™ has a wide selection from small and medium to large bird cages and ringneck doves for sale. Please visit our website for more info, Thank You.
2021年7月14日 20:02
Hire a professional magician for corporate event entertainment, Corporate Event Magician ,Wedding Party Entertainer, and more Doug Roy is a strolling magician and event entertainer, Doug has been obsessed with magic since he was a child and inspired by the greats – Houdini, Harry Blackstone, David Copperfield and David Baine. Please visit his website for more details and infromation. Wedding Party Entertainer
2021年7月22日 04:43
If You are at Airports Georgia and want to find store or supermarket but lost in a variety of terminals and complicated navigation. Here is the solution now you can quickly find the right store, kiosk, supermarket, boutique, or pharmacy at any airport around the world.
2021年7月25日 21:10
Nice post! This is a very nice blog that I will definitively come back to more times this year! Thanks for informative post. bola 88
2021年7月26日 22:30
A very excellent blog post. I am thankful for your blog post. I have found a lot of approaches after visiting your post. Europa Road kft
2021年7月27日 19:15
Five Star Towing & Transport Inc. - Servicing California & Nothern Nevada Five Star Towing Inc provide everything from light duty towing, medium duty towing to heavy duty towing sInce 1989 Servicing California and Northern Nevada, Please visit our website for more detailes and get a free qoute.
2021年7月29日 03:17
Howley Carpet Providing carpet cleaner cork service with professional and reliable Prices cleaning services to domestic and commercial customers in Fermoy, Co Cork, Please visit our website for more details, Thank You.
2021年7月31日 22:05
If You are looking to remove black magic forever. Instantly! | Using A Unique Method, remove black magic instantly efficiently Voodoo, spells, curses, programs, entities, spirits, buildings etc, Visit this website and get Free heading video, or get in touch for more detailes. Thank You. remove black magic
2021年8月02日 17:47
Many professional gamblers tend to stick to the most well-known online casinos with a good reputation. In fact, this is a very conscious and sound strategy for high rollers as they will only trust their money with the top online casino sites. However, this behaviour may also lead to the paradox of missing out on the biggest new casino bonuses. As a matter of fact, there are plenty of less known casinos out there who actually belong to the same casino network as the more popular ones - while offering better bonuses at the same time!<a href="https://betking777.com">메리트카지노</a>
2021年8月06日 18:17
Gamers who do not smoke prefer online casinos vs. land based casinos so that they do not have to breathe second hand smoke. People who do smoke may frequent a land-based casino where smoking has been banned, so they prefer the freedom of an online casino for gaming and smoking at will. Others have responsibilities at home with small children or other family members, and cannot always go to the casino when they want to. This assumes that there is a casino within driving distance of their home! Those who do not have the luxury of a land based casino close buy find that online casinos suit them perfectly.<a href="https://www.wooribet777.com">우리카지노</a>
2021年8月10日 04:56
It was a very good post indeed. I thoroughly enjoyed reading it in my lunch time. Will surely come and visit this blog more often. Thanks for sharing. cage crossfit alpha
2021年8月14日 17:22 Thank you very much for writing such an interesting article on this topic. This has really made me think and I hope to read more. tarot card reading near me
2021年8月21日 22:48
Thank you for this fascinating post, I am happy I observed this website on Google. Not just content, in fact, the whole site is fantastic. 먹튀폴리스
2021年8月23日 22:55
Thanks for a very interesting blog. What else may I get that kind of info written in such a perfect approach? I’ve a undertaking that I am simply now operating on, and I have been at the look out for such info. 검증사이트
2021年8月28日 15:04
I recently found many useful information in your website especially this blog page. Among the lots of comments on your articles. Thanks for sharing. wearable fashion
2021年9月02日 14:55
Very efficiently written information. It will be beneficial to anybody who utilizes it, including me. Keep up the good work. For sure i will check out more posts. This site seems to get a good amount of visitors. renaissance pet portraits
2021年9月13日 18:43
Excellent and very exciting site. Love to watch. Keep Rocking. บุหรี่ไฟฟ้า pod
2021年9月18日 22:07
Nice post! This is a very nice blog that I will definitively come back to more times this year! Thanks for informative post. Low Foot Chesterfield Beds
2021年9月19日 16:27
Hello I am so delighted I located your blog, I really located you by mistake, while I was watching on google for something else, Anyways I am here now and could just like to say thank for a tremendous post and a all round entertaining website. Please do keep up the great work. น้ำยาบุหรี่ไฟฟ้า
2021年9月20日 20:16
It proved to be Very helpful to me and I am sure to all the commentators here! บุหรี่ไฟฟ้า pod
2022年8月26日 02:57
ОТДЫХ ВСЕЙ СЕМЬЕЙ Особое внимание мы уделили детским программам, чтобы Вы могли полноценно расслабиться и насладиться отпуском. Отель в Крыму
2022年8月27日 23:57
Thanks for the informative and helpful post, obviously in your blog everything is good.. cbd großhandel preise
2022年8月28日 07:41
Wow! Such an amazing and helpful post this is. I really really love it. It's so good and so awesome. I am just amazed. I hope that you continue to do your work like this in the future also. Brands on Aliexpress
2022年9月01日 02:04
This is my first time i visit here. I found so many entertaining stuff in your blog, especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the leisure here! Keep up the good work. I have been meaning to write something like this on my website and you have given me an idea. 41215663