Search Results

Search found 406 results on 17 pages for 'dry'.

Page 3/17 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • What CSS compiler do you use (SASS, Less, HSS, etc)?

    - by T.R.
    I've been looking to make things a little more DRY, both on my personal projects (django) and at work (JSP/struts,PHP). SASS+HAML seem to be quite popular, but, do those outside of the Ruby/Rails community generally use these as well, or do they opt for other solutions? Which do you use, and what was the reasoning behind the choice?

    Read the article

  • Automark model names/attributes for translation

    - by Saosin
    Is there any way one could automatically mark all model names and attributes for translation, without specifying verbose_name/_plural on each one of them? Doesn't feel very DRY to do this every time: class Profile(models.Model): length = models.IntegerField(_('length')) weight = models.IntegerField(_('weight')) favorite_movies = models.CharField(_('favorite movies'), max_length=100) favorite_quote = models.CharField(_('favorite quote'), max_length=30) religious_views = models.CharField(_('religious views'), max_length=30) political_views = models.CharField(_('political views'), max_length=30) class Meta: verbose_name = _('profile') verbose_name_plural = _('profiles')

    Read the article

  • DRY programming dilemma

    - by fayer
    the situation is like this: im creating a Logger class that can write to a file but the write_to_file() function is in a helper class as a static function. i could call that function but then the Log class would be dependent to the helper class. isn't dependency bad? but if i can let it use a helper function then what is the point of having helper functions? what should one prioritize here: using helper functions and have to include this helper class everywhere (but the other 99 methods wont be useful) or just copy and paste into the Log class (but then if i have done this 100 times and then make a change i have to change in 100 places). share your thoughts and experience!

    Read the article

  • Rails - Seeking a Dry authorization method compatible with various nested resources

    - by adam
    Consensus is you shouldn't nest resources deeper than 1 level. So if I have 3 models like this (below is just a hypothetical situation) User has_many Houses has_many Tenants and to abide by the above i do map.resources :users, :has_many => :houses map.resorces :houses, :has_many => :tenants Now I want the user to be able edit both their houses and their tenants details but I want to prevent them from trying to edit another users houses and tenants by forging the user_id part of the urls. So I create a before_filter like this def prevent_user_acting_as_other_user if User.find_by_id(params[:user_id]) != current_user() @current_user_session.destroy flash[:error] = "Stop screwing around wiseguy" redirect_to login_url() return end end for houses that's easy because the user_id is passed via edit_user_house_path(@user, @house) but in the tenents case tenant house_tenent_path(@house) no user id is passed. But I can get the user id by doing @house.user.id but then id have to change the code above to this. def prevent_user_acting_as_other_user if params[:user_id] @user = User.find(params[:user_id] elsif params[:house_id] @user = House.find(params[:house_id]).user end if @user != current_user() #kick em out end end It does the job, but I'm wondering if there is a more elegant way. Every time I add a new resource that needs protecting from user forgery Ill have to keep adding conditionals. I don't think there will be many cases but would like to know a better approach if one exists.

    Read the article

  • DRY up Ruby ternary

    - by Reed G. Law
    I often have a situation where I want to do some conditional logic and then return a part of the condition. How can I do this without repeating the part of the condition in the true or false expression? For example: ClassName.method.blank? ? false : ClassName.method Is there any way to avoid repeating ClassName.method? Here is a real-world example: PROFESSIONAL_ROLES.key(self.professional_role).nil? ? 948460516 : PROFESSIONAL_ROLES.key(self.professional_role)

    Read the article

  • DRY jQuery for RESTful PUT/DELETE links

    - by Aupajo
    I'm putting together PUT/DELETE links, a la Rails, which when clicked create a POST form with an hidden input labelled _method that sends the intended request type. I want to make it DRYer, but my jQuery knowledge isn't up to it. HTML: <a href="/articles/1" class="delete">Destroy Article 1</a> <a href="/articles/1/publish" class="put">Publish Article 1</a> jQuery: $(document).ready(function() { $('.delete').click(function() { if(confirm('Are you sure?')) { var f = document.createElement('form'); $(this).after($(f).attr({ method: 'post', action: $(this).attr('href') }).append('<input type="hidden" name="_method" value="DELETE" />')); $(f).submit(); } return false; }); $('.put').click(function() { var f = document.createElement('form'); $(this).after($(f).attr({ method: 'post', action: $(this).attr('href') }).append('<input type="hidden" name="_method" value="PUT" />')); $(f).submit(); return false; }); });

    Read the article

  • More dry views?

    - by Pravin
    I have a simple index page for clients. Client has 20 fields. I am displaying list of clients in a table. For this I have to write in my views something like: - @clients.each do |client| %tr %td=client.name %td=client.email %td=client.address %td=client.phone etc... I am just curious if I can do it something like - @clients.each do |client| - client do %tr %td= name %td= email %td= address %td= phone etc...

    Read the article

  • Ruby Actions: How to avoid a bunch of returns to halt execution?

    - by Alexandre
    How can I DRY the code below? Do I have to setup a bunch of ELSEs ? I usually find the "if this is met, stop", "if this is met, stop", rather than a bunch of nested ifs. I discovered that redirect_to and render don't stop the action execution... def payment_confirmed confirm_payment do |confirmation| @purchase = Purchase.find(confirmation.order_id) unless @purchase.products_match_order_products?(confirmation.products) # TODO notify the buyer of problems return end if confirmation.status == :completed @purchase.paid! # TODO notify the user of completed purchase redirect_to purchase_path(@purchase) else # TODO notify the user somehow that thigns are pending end return end unless session[:last_purchase_id] flash[:notice] = 'Unable to identify purchase from session data.' redirect_to user_path(current_user) return end @purchase = Purchase.find(session[:last_purchase_id]) if @purchase.paid? redirect_to purchase_path(@purchase) return end # going to show message about pending payment end

    Read the article

  • Can I avoid repeating myself in this situation (Java)

    - by UltimateGuy
    if (openFile == null) { new AppFileDialog().chooseFile("Save", appFrame); } if (openFile == null) { return; } Here I need to check to see if the user has already chosen a file. If not, they are given a prompt to. If the file is still null, the function returns without saving. The problem is the two identical if statements, can I avoid it? I take DRY very seriously, but at the same time KISS. Ideally the two go hand in hand, but in a situation like this, it seems they are mutually exclusive.

    Read the article

  • Is Form validation and Business validation too much?

    - by Robert Cabri
    I've got this question about form validation and business validation. I see a lot of frameworks that use some sort of form validation library. You submit some values and the library validates the values from the form. If not ok it will show some errors on you screen. If all goes to plan the values will be set into domain objects. Here the values will be or, better said, should validated (again). Most likely the same validation in the validation library. I know 2 PHP frameworks having this kind of construction Zend/Kohana. When I look at programming and some principles like Don't Repeat Yourself (DRY) and single responsibility principle (SRP) this isn't a good way. As you can see it validates twice. Why not create domain objects that do the actual validation. Example: Form with username and email form is submitted. Values of the username field and the email field will be populated in 2 different Domain objects: Username and Email class Username {} class Email {} These objects validate their data and if not valid throw an exception. Do you agree? What do you think about this aproach? Is there a better way to implement validations? I'm confused about a lot of frameworks/developers handling this stuff. Are they all wrong or am I missing a point? Edit: I know there should also be client side kind of validation. This is a different ballgame in my Opinion. If You have some comments on this and a way to deal with this kind of stuff, please provide.

    Read the article

  • Ruby Design Problem for SQL Bulk Inserter

    - by crunchyt
    This is a Ruby design problem. How can I make a reusable flat file parser that can perform different data scrubbing operations per call, return the emitted results from each scrubbing operation to the caller and perform bulk SQL insertions? Now, before anyone gets narky/concerned, I have written this code already in a very unDRY fashion. Which is why I am asking any Ruby rockstars our there for some assitance. Basically, everytime I want to perform this logic, I create two nested loops, with custom processing in between, buffer each processed line to an array, and output to the DB as a bulk insert when the buffer size limit is reached. Although I have written lots of helpers, the main pattern is being copy pasted everytime. Not very DRY! Here is a Ruby/Pseudo code example of what I am repeating. lines_from_file.each do |line| line.match(/some regex/).each do |sub_str| # Process substring into useful format # EG1: Simple gsub() call # EG2: Custom function call to do complex scrubbing # and matching, emitting results to array # EG3: Loop to match opening/closing/nested brackets # or other delimiters and emit results to array end # Add processed lines to a buffer as SQL insert statement @buffer << PREPARED INSERT STATEMENT # Flush buffer when "buffer size limit reached" or "end of file" if sql_buffer_full || last_line_reached @dbc.insert(SQL INSERTS FROM BUFFER) @buffer = nil end end I am familiar with Proc/Lambda functions. However, because I want to pass two separate procs to the one function, I am not sure how to proceed. I have some idea about how to solve this, but I would really like to see what the real Rubyists suggest? Over to you. Thanks in advance :D

    Read the article

  • How can I implement CRUD operations in a base class for an entity framework app?

    - by hminaya
    I'm working a simple EF/MVC app and I'm trying to implement some Repositories to handle my entities. I've set up a BaseObject Class and a IBaseRepository Interface to handle the most basic operations so I don't have to repeat myself each time: public abstract class BaseObject<T> { public XA.Model.Entities.XAEntities db; public BaseObject() { db = new Entities.XAEntities(); } public BaseObject(Entities.XAEntities cont) { db = cont; } public void Delete(T entity) { db.DeleteObject(entity); db.SaveChanges(); } public void Update(T entity) { db.AcceptAllChanges(); db.SaveChanges(); } } public interface IBaseRepository<T> { void Add(T entity); T GetById(int id); IQueryable<T> GetAll(); } But then I find myself having to implement 3 basic methods in every Repository ( Add, GetById & GetAll): public class AgencyRepository : Framework.BaseObject<Agency>, Framework.IBaseRepository<Agency> { public void Add(Agency entity) { db.Companies.AddObject(entity); db.SaveChanges(); } public Agency GetById(int id) { return db.Companies.OfType<Agency>().FirstOrDefault(x => x.Id == id); } public IQueryable<Agency> GetAll() { var agn = from a in db.Companies.OfType<Agency>() select a; return agn; } } How can I get these into my BaseObject Class so I won't run in conflict with DRY.

    Read the article

  • What are DRY, KISS, SOLID, etc. classified as?

    - by Morgan Herlocker
    Is something like DRY a design pattern, a methodology, or something in between? They do not have specific implementations that could neccessarily be demonstrated(even if you can easily demonstrate a case NOT using something like KISS... see The Daily WTF for a plethora of examples), nor do they fully explain a development process like a methodology generally would. Where does that leave these types of "rule of thumb"'s?

    Read the article

  • Re-using aggregate level formulas in SQL - any good tactics?

    - by Cade Roux
    Imagine this case, but with a lot more component buckets and a lot more intermediates and outputs. Many of the intermediates are calculated at the detail level, but a few things are calculated at the aggregate level: DECLARE @Profitability AS TABLE ( Cust INT NOT NULL ,Category VARCHAR(10) NOT NULL ,Income DECIMAL(10, 2) NOT NULL ,Expense DECIMAL(10, 2) NOT NULL ) ; INSERT INTO @Profitability VALUES ( 1, 'Software', 100, 50 ) ; INSERT INTO @Profitability VALUES ( 2, 'Software', 100, 20 ) ; INSERT INTO @Profitability VALUES ( 3, 'Software', 100, 60 ) ; INSERT INTO @Profitability VALUES ( 4, 'Software', 500, 400 ) ; INSERT INTO @Profitability VALUES ( 5, 'Hardware', 1000, 550 ) ; INSERT INTO @Profitability VALUES ( 6, 'Hardware', 1000, 250 ) ; INSERT INTO @Profitability VALUES ( 7, 'Hardware', 1000, 700 ) ; INSERT INTO @Profitability VALUES ( 8, 'Hardware', 5000, 4500 ) ; SELECT Cust ,Profit = SUM(Income - Expense) ,Margin = SUM(Income - Expense) / SUM(Income) FROM @Profitability GROUP BY Cust SELECT Category ,Profit = SUM(Income - Expense) ,Margin = SUM(Income - Expense) / SUM(Income) FROM @Profitability GROUP BY Category SELECT Profit = SUM(Income - Expense) ,Margin = SUM(Income - Expense) / SUM(Income) FROM @Profitability Notice how the same formulae have to be used at the different aggregation levels. This results in code duplication. I have thought of using UDFs (either scalar or table valued with an OUTER APPLY, since many of the final results may share intermediates which have to be calculated at the aggregate level), but in my experience the scalar and multi-statement table-valued UDFs perform very poorly. Also thought about using more dynamic SQL and applying the formulas by name, basically. Any other tricks, techniques or tactics to keeping these kinds of formulae which need to be applied at different levels in sync and/or organized?

    Read the article

  • How to implement or emulate an "abstract" OCUnit test class?

    - by Quinn Taylor
    I have a number of Objective-C classes organized in an inheritance hierarchy. They all share a common parent which implements all the behaviors shared among the children. Each child class defines a few methods that make it work, and the parent class raises an exception for the methods designed to be implemented/overridden by its children. This effectively makes the parent a pseudo-abstract class (since it's useless on its own) even though Objective-C doesn't explicitly support abstract classes. The crux of this problem is that I'm unit testing this class hierarchy using OCUnit, and the tests are structured similarly: one test class that exercises the common behavior, with a subclass corresponding to each of the child classes under test. However, running the test cases on the (effectively abstract) parent class is problematic, since the unit tests will fail in spectacular fashion without the key methods. (The alternative of repeating the common tests across 5 test classes is not really an acceptable option.) The non-ideal solution I've been using is to check (in each test method) whether the instance is the parent test class, and bail out if it is. This leads to repeated code in every test method, a problem that becomes increasingly annoying if one's unit tests are highly granular. In addition, all such tests are still executed and reported as successes, skewing the number of meaningful tests that were actually run. What I'd prefer is a way to signal to OCUnit "Don't run any tests in this class, only run them in its child classes." To my knowledge, there isn't (yet) a way to do that, something similar to a +(BOOL)isAbstractTest method I can implement/override. Any ideas on a better way to solve this problem with minimal repetition? Does OCUnit have any ability to flag a test class in this way, or is it time to file a Radar? Edit: Here's a link to the test code in question. Notice the frequent repetition of if (...) return; to start a method, including use of the NonConcreteClass() macro for brevity.

    Read the article

  • How to specify a parameter as part of every web service call?

    - by LES2
    Currently, each web service for our application has a user parameter that is added for every method. For example: @WebService public interface FooWebService { @WebMethod public Foo getFoo(@WebParam(name="alwaysHere",header=true,partName="alwaysHere") String user, @WebParam(name="fooId") Long fooId); @WebMethod public Result deletetFoo(@WebParam(name="alwaysHere",header=true,partName="alwaysHere") String user, @WebParam(name="fooId") Long fooId); // ... } There could be twenty methods in a service, each with the first parameter as user. And there could be twenty web services. We don't actually use the 'user' argument in the implementations - in fact, I don't know why it's there - but I wasn't involved in the design, and the person that put it there had a reason (I hope). Anyway, I'm trying to straighten out this Big Ball of Mud. I have already come a long way by wrapping the web services by a Spring proxy, which allows me to do some before-and-after processing in an interceptor (before there were at least 20 lines of copy-pasted boiler plate per method). I'm wondering if there's some kind of "message header" I can apply to the method or package and that can be accessed by some type of handler or something outside of each web service method. Thanks in advance for the advice, LES

    Read the article

  • How can my-program.hs get its version number from my-program.cabal at build time?

    - by Dave Hinton
    I would like my cabalised program to have a --version switch. I would like it to report the same version as is present in the .cabal file. If I have to update the version number separately in my Haskell source code as well as in the .cabal file, I will eventually get them out of sync. So, how can my program, while being compiled under cabal, get its version number from the .cabal file?

    Read the article

  • How do I initialize attributes when I instantiate objects in Rails?

    - by nfm
    Clients have many Invoices. Invoices have a number attribute that I want to initialize by incrementing the client's previous invoice number. For example: @client = Client.find(1) @client.last_invoice_number > 14 @invoice = @client.invoices.build @invoice.number > 15 I want to get this functionality into my Invoice model, but I'm not sure how to. Here's what I'm imagining the code to be like: class Invoice < ActiveRecord::Base ... def initialize(attributes = {}) client = Client.find(attributes[:client_id]) attributes[:number] = client.last_invoice_number + 1 client.update_attributes(:last_invoice_number => client.last_invoice_number + 1) end end However, attributes[:client_id] isn't set when I call @client.invoices.build. How and when is the invoice's client_id initialized, and when can I use it to initialize the invoice's number? Can I get this logic into the model, or will I have to put it in the controller?

    Read the article

  • Django - Tips to avoid repeating code in views

    - by D Roddis
    I'm moving from a PHP background into Django development via python, mostly for the sake of tackling a MVC (or MVT) that I feel makes the most sense, although in this pattern I've started to notice a lot of repeated code in my views. For example, when logged in I have information regarding the user that I would like to appear on every page, although when using render_to_response and in every view this is required I have to grab the information and pass it to the render_to_response function. I'm wondering what would be the most efficient way to cut down on the duplicate code which would in essence be required in all views in a particular app. Thanks in advance.

    Read the article

  • An exception to avoid copy and paste code?

    - by Jian Lin
    There are many files in our project that would call a Facebook api. And the call is complicated, spanning usually 8 lines or more, just for the argument values. In this case, we can make it into a function, and place that function in a common_library.php, but doing so would just change the name of the function call from the Facebook API function to our name, and we still need to repeat the 8 lines of arguments. Each time, the call is very similar, but with slight variations to the argument values. In that case, would copy and paste be needed no matter what we do?

    Read the article

  • DRYing out implementation of ICloneable in several classes

    - by Sarah Vessels
    I have several different classes that I want to be cloneable: GenericRow, GenericRows, ParticularRow, and ParticularRows. There is the following class hierarchy: GenericRow is the parent of ParticularRow, and GenericRows is the parent of ParticularRows. Each class implements ICloneable because I want to be able to create deep copies of instances of each. I find myself writing the exact same code for Clone() in each class: object ICloneable.Clone() { object clone; using (var stream = new MemoryStream()) { var formatter = new BinaryFormatter(); // Serialize this object formatter.Serialize(stream, this); stream.Position = 0; // Deserialize to another object clone = formatter.Deserialize(stream); } return clone; } I then provide a convenience wrapper method, for example in GenericRows: public GenericRows Clone() { return (GenericRows)((ICloneable)this).Clone(); } I am fine with the convenience wrapper methods looking about the same in each class because it's very little code and it does differ from class to class by return type, cast, etc. However, ICloneable.Clone() is identical in all four classes. Can I abstract this somehow so it is only defined in one place? My concern was that if I made some utility class/object extension method, it would not correctly make a deep copy of the particular instance I want copied. Is this a good idea anyway?

    Read the article

  • More elegant way to make a C++ member function change different member variables based on template p

    - by Eric Moyer
    Today, I wrote some code that needed to add elements to different container variables depending on the type of a template parameter. I solved it by writing a friend helper class specialized on its own template parameter which had a member variable of the original class. It saved me a few hundred lines of repeating myself without adding much complexity. However, it seemed kludgey. I would like to know if there is a better, more elegant way. The code below is a greatly simplified example illustrating the problem and my solution. It compiles in g++. #include <vector> #include <algorithm> #include <iostream> namespace myNS{ template<class Elt> struct Container{ std::vector<Elt> contents; template<class Iter> void set(Iter begin, Iter end){ contents.erase(contents.begin(), contents.end()); std::copy(begin, end, back_inserter(contents)); } }; struct User; namespace WkNS{ template<class Elt> struct Worker{ User& u; Worker(User& u):u(u){} template<class Iter> void set(Iter begin, Iter end); }; }; struct F{ int x; explicit F(int x):x(x){} }; struct G{ double x; explicit G(double x):x(x){} }; struct User{ Container<F> a; Container<G> b; template<class Elt> void doIt(Elt x, Elt y){ std::vector<Elt> v; v.push_back(x); v.push_back(y); Worker<Elt>(*this).set(v.begin(), v.end()); } }; namespace WkNS{ template<class Elt> template<class Iter> void Worker<Elt>::set(Iter begin, Iter end){ std::cout << "Set a." << std::endl; u.a.set(begin, end); } template<> template<class Iter> void Worker<G>::set(Iter begin, Iter end){ std::cout << "Set b." << std::endl; u.b.set(begin, end); } }; }; int main(){ using myNS::F; using myNS::G; myNS::User u; u.doIt(F(1),F(2)); u.doIt(G(3),G(4)); } User is the class I was writing. Worker is my helper class. I have it in its own namespace because I don't want it causing trouble outside myNS. Container is a container class whose definition I don't want to modify, but is used by User in its instance variables. doIt<F> should modify a. doIt<G> should modify b. F and G are open to limited modification if that would produce a more elegant solution. (As an example of one such modification, in the real application F's constructor takes a dummy parameter to make it look like G's constructor and save me from repeating myself.) In the real code, Worker is a friend of User and member variables are private. To make the example simpler to write, I made everything public. However, a solution that requires things to be public really doesn't answer my question. Given all these caveats, is there a better way to write User::doIt?

    Read the article

  • Template function as a template argument

    - by Kos
    I've just got confused how to implement something in a generic way in C++. It's a bit convoluted, so let me explain step by step. Consider such code: void a(int) { // do something } void b(int) { // something else } void function1() { a(123); a(456); } void function2() { b(123); b(456); } void test() { function1(); function2(); } It's easily noticable that function1 and function2 do the same, with the only different part being the internal function. Therefore, I want to make function generic to avoid code redundancy. I can do it using function pointers or templates. Let me choose the latter for now. My thinking is that it's better since the compiler will surely be able to inline the functions - am I correct? Can compilers still inline the calls if they are made via function pointers? This is a side-question. OK, back to the original point... A solution with templates: void a(int) { // do something } void b(int) { // something else } template<void (*param)(int) > void function() { param(123); param(456); } void test() { function<a>(); function<b>(); } All OK. But I'm running into a problem: Can I still do that if a and b are generics themselves? template<typename T> void a(T t) { // do something } template<typename T> void b(T t) { // something else } template< ...param... > // ??? void function() { param<SomeType>(someobj); param<AnotherType>(someotherobj); } void test() { function<a>(); function<b>(); } I know that a template parameter can be one of: a type, a template type, a value of a type. None of those seems to cover my situation. My main question is hence: How do I solve that, i.e. define function() in the last example? (Yes, function pointers seem to be a workaround in this exact case - provided they can also be inlined - but I'm looking for a general solution for this class of problems).

    Read the article

  • Refactoring code/consolidating functions (e.g. nested for-loop order)

    - by bmay2
    Just a little background: I'm making a program where a user inputs a skeleton text, two numbers (lower and upper limit), and a list of words. The outputs are a series of modifications on the skeleton text. Sample inputs: text = "Player # likes @." (replace # with inputted integers and @ with words in list) lower = 1 upper = 3 list = "apples, bananas, oranges" The user can choose to iterate over numbers first: Player 1 likes apples. Player 2 likes apples. Player 3 likes apples. Or words first: Player 1 likes apples. Player 1 likes bananas. Player 1 likes oranges. I chose to split these two methods of outputs by creating a different type of dictionary based on either number keys (integers inputted by the user) or word keys (from words in the inputted list) and then later iterating over the values in the dictionary. Here are the two types of dictionary creation: def numkey(dict): # {1: ['Player 1 likes apples', 'Player 1 likes...' ] } text, lower, upper, list = input_sort(dict) d = {} for num in range(lower,upper+1): l = [] for i in list: l.append(text.replace('#', str(num)).replace('@', i)) d[num] = l return d def wordkey(dict): # {'apples': ['Player 1 likes apples', 'Player 2 likes apples'..] } text, lower, upper, list = input_sort(dict) d = {} for i in list: l = [] for num in range(lower,upper+1): l.append(text.replace('#', str(num)).replace('@', i)) d[i] = l return d It's fine that I have two separate functions for creating different types of dictionaries but I see a lot of repetition between the two. Is there any way I could make one dictionary function and pass in different values to it that would change the order of the nested for loops to create the specific {key : value} pairs I'm looking for? I'm not sure how this would be done. Is there anything related to functional programming or other paradigms that might help with this? The question is a little abstract and more stylistic/design-oriented than anything.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >